重写实例上的特殊方法
- 2024-12-13 08:37:00
- admin 原创
- 128
问题描述:
考虑以下代码:
>>> class A(object):
... pass
...
>>> def __repr__(self):
... return "A"
...
>>> from types import MethodType
>>> a = A()
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>> setattr(a, "__repr__", MethodType(__repr__, a, a.__class__))
>>> a
<__main__.A object at 0x00AC6990>
>>> repr(a)
'<__main__.A object at 0x00AC6990>'
>>>
注意到 repr(a) 没有产生预期结果“A”吗?我想知道为什么会这样,以及是否有办法实现这一点...
相反,下面的例子却有效(可能是因为我们没有尝试覆盖特殊方法?):
>>> class A(object):
... def foo(self):
... return "foo"
...
>>> def bar(self):
... return "bar"
...
>>> from types import MethodType
>>> a = A()
>>> a.foo()
'foo'
>>> setattr(a, "foo", MethodType(bar, a, a.__class__))
>>> a.foo()
'bar'
>>>
解决方案 1:
Python 通常不会__
在实例上调用特殊方法(名称被 包围的方法),而只会在类上调用。(虽然这是一个实现细节,但它是标准解释器 CPython 的特征。)因此无法__repr__()
直接在实例上覆盖并使其工作。相反,您需要执行以下操作:
class A(object):
def __repr__(self):
return self._repr()
def _repr(self):
return object.__repr__(self)
现在您可以__repr__()
通过替换来覆盖实例_repr()
。
解决方案 2:
正如特殊方法查找中解释的那样:
对于自定义类,隐式调用特殊方法只有在对象类型上定义,而不是在对象实例字典中定义时才能保证正常工作……除了为了正确性而绕过任何实例属性外,隐式特殊方法查找通常还会绕过
__getattribute__()
对象元类的方法
(如果您感兴趣的话,我剪掉的部分解释了这背后的原因。)
Python 并没有确切地记录实现何时应该或不应该在类型上查找方法;实际上,它所记录的全部内容是,实现可能会或可能不会查看实例以进行特殊方法查找,因此您不应该依赖这两者。
从测试结果中您可以猜测到,在 CPython 实现中,__repr__
是在该类型上查找的函数之一。
2.x 中的情况略有不同,主要是因为存在经典类,但只要您只创建新式类,您就可以将它们视为相同的。
人们想要这样做的最常见原因是对对象的不同实例进行 monkey-patch 以执行不同的操作。您无法使用特殊方法做到这一点,那么……您能做什么?有一个干净的解决方案和一个 hack 解决方案。
干净的解决方案是在类上实现一个特殊方法,该方法只调用实例上的常规方法。然后,您可以在每个实例上对该常规方法进行 monkey patch。例如:
class C(object):
def __repr__(self):
return getattr(self, '_repr')()
def _repr(self):
return 'Boring: {}'.format(object.__repr__(self))
c = C()
def c_repr(self):
return "It's-a me, c_repr: {}".format(object.__repr__(self))
c._repr = c_repr.__get__(c)
最不靠谱的解决方案是动态构建一个新的子类并重新对对象进行分类。我怀疑任何真正遇到过这种想法的人都会知道如何从这句话中实现它,而任何不知道如何实现的人都不应该尝试,所以我就到此为止了。
解决方案 3:
原因在于特殊方法(__x__()
)是为类而不是实例定义的。
如果您仔细想想的话,就会明白这很有道理__new__()
——在实例上调用它是不可能的,因为调用它时实例并不存在。
因此,如果您愿意,您可以在整个班级范围内执行此操作:
>>> A.__repr__ = __repr__
>>> a
A
或者针对单个实例,如kindall 的回答。(请注意,这里有很多相似之处,但我认为我的例子足以发布这一点)。
解决方案 4:
对于新式类,Python 使用一种绕过实例的特殊方法查找。以下是源代码的摘录:
1164 /* Internal routines to do a method lookup in the type
1165 without looking in the instance dictionary
1166 (so we can't use PyObject_GetAttr) but still binding
1167 it to the instance. The arguments are the object,
1168 the method name as a C string, and the address of a
1169 static variable used to cache the interned Python string.
1170
1171 Two variants:
1172
1173 - lookup_maybe() returns NULL without raising an exception
1174 when the _PyType_Lookup() call fails;
1175
1176 - lookup_method() always raises an exception upon errors.
1177
1178 - _PyObject_LookupSpecial() exported for the benefit of other places.
1179 */
您可以更改为旧式类(不从object继承),也可以向类添加调度程序方法(将查找转发回实例的方法)。有关实例调度程序方法的示例,请参阅http://code.activestate.com/recipes/578091上的配方
解决方案 5:
TLDR:无法在实例上定义适当的、未绑定的方法;这也适用于特殊方法。由于绑定方法是一等对象,因此在某些情况下差异并不明显。但是,在需要时,Python 始终会将特殊方法查找为适当的、未绑定的方法。
您始终可以手动回退到使用更通用的属性访问的特殊方法。属性访问涵盖存储为属性的绑定方法以及根据需要绑定的非绑定方法。这类似于__repr__
或其他方法使用属性来定义其输出的方式。
class A:
def __init__(self, name):
self.name = name
def __repr__(self):
# call attribute to derive __repr__
return self.__representation__()
def __representation__(self):
return f'{self.__class__.__name__}({self.name})'
def __str__(self):
# return attribute to derive __str__
return self.name
非绑定方法与绑定方法
Python 中的方法有两种含义:类的未绑定方法和该类实例的绑定方法。
未绑定方法是类或其基类上的常规函数。它可以在类定义期间定义,也可以稍后添加。
>>> class Foo:
... def bar(self): print('bar on', self)
...
>>> Foo.bar
<function __main__.Foo.bar(self)>
未绑定方法在类中仅存在一次 - 对于所有实例来说都是相同的。
绑定方法是一种未绑定方法,它已绑定到特定实例。这通常意味着该方法是通过实例查找的,它会调用函数的__get__
方法。
>>> foo = Foo()
>>> # lookup through instance
>>> foo.bar
<bound method Foo.bar of <__main__.Foo object at 0x10c3b6390>>
>>> # explicit descriptor invokation
>>> type(foo).bar.__get__(foo, Foo)
<bound method Foo.bar of <__main__.Foo object at 0x10c3b6390>>
就 Python 而言,“方法”通常是指按要求绑定到其实例的未绑定方法。当 Python 需要特殊方法时,它会直接调用未绑定方法的描述符协议。结果,在类上查找该方法;实例上的属性被忽略。
对象的绑定方法
每次从实例中获取绑定方法时,都会重新创建该方法。结果是一个具有身份、可存储和传递并在以后调用的一级对象。
>>> foo.bar is foo.bar # binding happens on every lookup
False
>>> foo_bar = foo.bar # bound methods can be stored
>>> foo_bar() # stored bound methods can be called later
bar on <__main__.Foo object at 0x10c3b6390>
>>> foo_bar()
bar on <__main__.Foo object at 0x10c3b6390>
能够存储绑定方法意味着它们也可以作为属性存储。将绑定方法存储在其绑定实例上使其看起来与未绑定方法相似。但实际上,存储的绑定方法的行为略有不同,并且可以存储在允许属性的任何对象上。
>>> foo.qux = foo.bar
>>> foo.qux
<bound method Foo.bar of <__main__.Foo object at 0x10c3b6390>>
>>> foo.qux is foo.qux # binding is not repeated on every lookup!
True
>>> too = Foo()
>>> too.qux = foo.qux # bound methods can be stored on other instances!
>>> too.qux # ...but are still bound to the original instance!
<bound method Foo.bar of <__main__.Foo object at 0x10c3b6390>>
>>> import builtins
>>> builtins.qux = foo.qux # bound methods can be stored...
>>> qux # ... *anywhere* that supports attributes
<bound method Foo.bar of <__main__.Foo object at 0x10c3b6390>>
就 Python 而言,绑定方法只是常规的可调用对象。正如它无法知道 是否too.qux
是 的方法一样too
,它也无法推断 是否too.__repr__
是 方法。