Python:在运行时更改方法和属性
问题描述:
我希望在 Python 中创建一个可以添加和删除属性和方法的类.我怎样才能做到这一点?
I wish to create a class in Python that I can add and remove attributes and methods. How can I acomplish that?
哦,请不要问为什么.
答
我希望在 Python 中创建一个可以添加和删除属性和方法的类.
I wish to create a class in Python that I can add and remove attributes and methods.
import types
class SpecialClass(object):
@classmethod
def removeVariable(cls, name):
return delattr(cls, name)
@classmethod
def addMethod(cls, func):
return setattr(cls, func.__name__, types.MethodType(func, cls))
def hello(self, n):
print n
instance = SpecialClass()
SpecialClass.addMethod(hello)
>>> SpecialClass.hello(5)
5
>>> instance.hello(6)
6
>>> SpecialClass.removeVariable("hello")
>>> instance.hello(7)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'SpecialClass' object has no attribute 'hello'
>>> SpecialClass.hello(8)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'SpecialClass' has no attribute 'hello'