我已经读过可以在Python中向现有对象(即,不在类定义中)添加方法.
我知道这样做并不总是好事.但是人们怎么可能这样做呢?
我希望在Python中创建一个可以添加和删除属性和方法的类.我该怎么做呢?
哦,请不要问为什么.
经过大量搜索,我发现有几种方法可以将绑定方法或未绑定类方法添加到现有实例对象
这些方式包括以下代码采用的方法.
import types
class A(object):
pass
def instance_func(self):
print 'hi'
def class_func(self):
print 'hi'
a = A()
# add bound methods to an instance using type.MethodType
a.instance_func = types.MethodType(instance_func, a) # using attribute
a.__dict__['instance_func'] = types.MethodType(instance_func, a) # using __dict__
# add bound methods to an class
A.instance_func = instance_func
A.__dict__['instance_func'] = instance_func
# add class methods to an class
A.class_func = classmethod(class_func)
A.__dict__['class_func'] = classmethod(class_func)
Run Code Online (Sandbox Code Playgroud)
让我讨厌的是,键入函数的名称,instance_func或class_func两次.
有没有简单的方法将现有函数添加到类或实例而不再键入函数的名称?
例如,
A.add_function_as_bound_method(f)由于函数已经具有__name__属性,因此将现有函数添加到实例或类将是非常优雅的方式.