【发布时间】:2012-05-16 02:12:38
【问题描述】:
是否可以使用setattr() 为类实例动态分配特殊方法,例如__getitem__?例如,如果我有这个:
class Example (object):
pass
然后试试这个:
>>> example = Example()
>>> setattr(example, '__getitem__', lambda x: 1)
我明白了:
>>> example['something']
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'Example' object has no attribute '__getitem__'
当然,这很好用:
>>> example.__getitem__('something')
1
这里显然发生了一些我不明白的事情,关于 Python 如何为这类事情进行方法查找。这些方法是否必须在类上设置,而不是在实例上?
更新:
所以,我应该说清楚,我知道我可以在 Example 类上看到这个...我希望有一种方法可以按实例设置它们,但共识到目前为止,我看到的是你不能那样做。
【问题讨论】:
标签: python introspection setattr