对象动态添加方法

动态添加属性很简单,obj.attr = value

In [19]: class Person(object):
   ....:     def __init__(self, name):
   ....:         self.name = name
   ....:         
In [20]: p1 = Person('Yo')
In [21]: p1.name
Out[21]: 'Yo'
In [22]: p1.age = 21
In [23]: p1.age
Out[23]: 21

动态添加方法比较麻烦,因为需要传入self

In [24]: def run(self):
   ....:     print('---Run: {}---'.format(self.name))
   ....:     
In [25]: p1.run = run(p1)
---Run: Yo---
In [26]: p1.run
In [27]: p1.run()
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-27-d4221f21b5ea> in <module>()
----> 1 p1.run()

TypeError: 'NoneType' object is not callable

动态添加实例方法

通过types.MethodType方法可以实现这个需求


In [28]: import types

In [29]: p1.run = types.Me
types.MemberDescriptorType  types.MethodType            

In [29]: p1.run = types.MethodType(run, p1)

In [30]: p1.run()
---Run: Yo---

动态添加静态方法

In [34]: @staticmethod
   ....: def eat():
   ....:     print('---eat---')
   ....:     
In [35]: Person.eat = eat
In [36]: Person.eat()

动态添加类方法

In [43]: @classmethod
   ....: def talk(cls):
   ....:     print('---talk---')
   ....:     
In [44]: Person.talk = talk
In [45]: Person.talk()
---talk---

results matching ""

    No results matching ""