Python 之动态添加属性以及方法

import types


class Person(object):
    def __init__(self, newName, newAge):
        self.name = newName
        self.age = newAge

def run(self):
    print("%s is running..." % self.name)

# 静态方法
@staticmethod
def test():
    print("static method...")

# 类方法
@classmethod
def eat(cls):
    print("class method...")

if __name__ == "__main__":
    p = Person('yy', 18)
    # 给person类添加一个属性
    p.id = 12;

    # 给person类添加一个方法
    p.run = run
    p.run(p)
    # 方式二
    p.run = types.MethodType(run, p)
    p.run()

    # 给person类添加一个静态方法
    Person.test = test
    Person.test()

    # 给person类添加一个类方法
    Person.eat = eat
    Person.eat()
    print(dir(p))
原文地址:https://www.cnblogs.com/yang-2018/p/10849750.html