【问题标题】:Setting special methods using setattr()使用 setattr() 设置特殊方法
【发布时间】: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


    【解决方案1】:

    这里的问题是__getitem__() 是在类级别定义的,而不是在实例级别:

    >>> class Example (object):
    ...     pass
    ... 
    >>> example = Example()
    >>> setattr(Example, '__getitem__', lambda x, y: 1)
    >>> example['something']
    1
    

    如果您需要它是特定于实例的:

    >>> class Example(object):
    ...     def __getitem__(self, item):
    ...         return self._getitem(item)
    ... 
    >>> example = Example()
    >>> setattr(example, '_getitem', lambda x: 1)
    >>> example['something']
    1
    >>> example2 = Example()
    >>> setattr(example2, '_getitem', lambda x: 2)
    >>> example['something']
    1
    >>> example2['something']
    2
    

    【讨论】:

    • 嗯...但这会影响Example的所有实例,而不仅仅是特定实例。回到我的绘图板上,我猜。
    • @larsks 让__getitem__() 在实例上调用函数非常简单。我将添加一个示例。
    【解决方案2】:

    您是否尝试猴子修补类,而不是实例?

    >>> example = Example()
    >>> setattr(Example, '__getitem__', lambda self,x: 1)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-18
      • 2018-08-14
      • 2014-07-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-11
      相关资源
      最近更新 更多