Python:在运行时更改方法和属性

我希望在Python中创建一个可以添加和删除属性和方法的类。我该如何完成?

哦,请不要问为什么。


慕娘9325324
浏览 494回答 3
3回答

精慕HU

我希望在Python中创建一个可以添加和删除属性和方法的类。import typesclass SpecialClass(object):&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def removeVariable(cls, name):&nbsp; &nbsp; &nbsp; &nbsp; return delattr(cls, name)&nbsp; &nbsp; @classmethod&nbsp; &nbsp; def addMethod(cls, func):&nbsp; &nbsp; &nbsp; &nbsp; return setattr(cls, func.__name__, types.MethodType(func, cls))def hello(self, n):&nbsp; &nbsp; 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):&nbsp; File "<stdin>", line 1, in <module>AttributeError: 'SpecialClass' object has no attribute 'hello'>>> SpecialClass.hello(8)Traceback (most recent call last):&nbsp; File "<stdin>", line 1, in <module>AttributeError: type object 'SpecialClass' has no attribute 'hello'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python