python 动态添加实例对象的属性和方法

python学习网 2017-12-26 16:15:02

正常情况:

 1 class Person():
 2 
 3     def __init__(self, name):
 4         self.name = name
 5 
 6     def eat(self, food):    # 属于类对象
 7         print('吃%s...' % food)
 8 
 9 
10 p = Person('wang')
11 print(p.name)
12 p.eat('蛋糕')
13 print(Person.__dict__)
14 print(p.__dict__)
1 wang
2 吃蛋糕...
3 {'__module__': '__main__', '__init__': <function Person.__init__ at 0x00000000023338C8>, 'eat': <function Person.eat at 0x0000000002333730>, '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
4 {'name': 'wang'}

动态方法添加

 1 class Person():
 2     pass
 3 
 4 
 5 def eat(food):
 6     print('吃%s...' % food)
 7 
 8 
 9 p = Person()
10 p.name = 'wang'
11 p.eat = eat   # 属于实例对象,与上面的是有区别的
12 print(p.name)
13 p.eat('蛋糕')
14 print(Person.__dict__)
15 print(p.__dict__)
1 wang
2 吃蛋糕...
3 {'__module__': '__main__', '__dict__': <attribute '__dict__' of 'Person' objects>, '__weakref__': <attribute '__weakref__' of 'Person' objects>, '__doc__': None}
4 {'name': 'wang', 'eat': <function eat at 0x00000000027E90D0>}

 

 

阅读(839) 评论(0)