我希望在Python中创建一个可以添加和删除属性和方法的类。
import typesclass 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 ninstance = 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'
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)