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))

 

相关文章:

  • 2022-12-23
  • 2021-08-03
  • 2021-09-07
  • 2022-12-23
  • 2022-12-23
  • 2021-05-17
  • 2022-01-24
猜你喜欢
  • 2021-12-21
  • 2021-06-27
  • 2021-04-25
  • 2021-12-07
  • 2021-04-16
  • 2022-12-23
  • 2022-12-23
相关资源
相似解决方案