---恢复内容开始---
python动态添加属性:
1 class Person(object): 2 def __init__(self,newName,newAge): 3 self.name = newName 4 self.age = newAge 5 6 laowang = Person("laowang",20) 7 print(laowang.name) 8 print(laowang.age) 9 laowang.addr = "北京"#动态添加的属性addr 10 print(laowang .addr)
python动态添加方法:
1 import types 2 class Person(object): 3 def __init__(self,newName,newAge): 4 self.name = newName 5 self.age = newAge 6 def eat(self): 7 print("...%s正在吃。。"%self.name) 8 def run(self): 9 print("...%s正在跑。。"%self.name) 10 Wang = Person("laowang",20) 11 Wang.eat() 12 Wang.run = types.MethodType(run,Wang)#将run这个函数添加为方法 13 Wang.run()
python添加静态方法和类方法,注意点,静态方法和类方法都是与类关联的
1 class Person(object): 2 def __init__(self,newName,newAge): 3 self.name = newName 4 self.age = newAge 5 def eat(self): 6 print("...%s正在吃。。"%self.name) 7 @staticmethod#静态方法 8 def test(): 9 print("...static method...") 10 @classmethod#类方法 11 def test1(cls): 12 print("...class method...") 13 laowang= Person("laowang",20) 14 Person.test = test#添加静态方法,静态方法跟着类走的 15 Person.test() 16 Person.test1 = test1#添加类方法,类方法跟着类走的 17 Person.test1()
---恢复内容结束---