Python:在运行时更改方法和属性 [英] Python: changing methods and attributes at runtime
本文介绍了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'
这篇关于Python:在运行时更改方法和属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文