在python中,是否可以从对象(而不是类)中删除方法?

2024-09-28 22:03:04 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个带有几个方法的类,其中一些方法只有在对象处于特定状态时才有效。我想让这些方法在对象不处于合适的状态时不绑定到它们,这样我就可以得到如下结果:

>>> wiz=Wizard()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.addmana()
>>> dir(wiz)
['__doc__', '__module__', 'addmana', 'domagic']
>>> wiz.domagic()
>>> dir(wiz)
['__doc__', '__module__', 'addmana']
>>> wiz.domagic()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'

我可以看到如何添加方法(types.MethodType(method,object)),但我看不到任何方法可以删除仅用于单个对象的方法:

>>> wiz.domagic
<bound method Wizard.domagic of <__main__.Wizard instance at 0x7f0390d06950>>
>>> del wiz.domagic
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: Wizard instance has no attribute 'domagic'

重写dir(并在调用时获取InvalidState或NotEnoughMana异常,而不是在引用时获取attributeRor)可能没问题,但我看不到如何准确地模拟dir()的内置行为。(理想情况下,我也更喜欢在Python2.5中工作的方式)

有什么想法?


Tags: 对象方法instancemostdoc状态dircall