两个相关的问题。首先是上下文:
来自 python documentation :
These are the so-called “rich comparison” methods. The correspondence between operator symbols and method names is as follows: xlt(y), x<=y calls x.le(y), x==y calls x.eq(y), x!=y calls x.ne(y), x>y calls x.gt(y), and x>=y calls x.ge(y).
考虑以下几点:
class Foo:
def __getattribute__(self, attr):
print(attr)
return super(Foo, self).__getattribute__(attr)
foo = Foo()
我希望在 foo 上调用的任何函数都应该被打印出来,对吗?从文档中,我希望如果我执行
foo < 1
那么这应该等于
foo.__lt__(1)
这又应该调用 foo.__getattribute__('__lt__'),对吗?
但事实并非如此。相反,我看到的是对 __class__ 属性的两个请求:
In [135]: foo < 1
__class__
__class__
Traceback (most recent call last):
File "<ipython-input-135-ee30676e9187>", line 1, in <module>
foo < 1
TypeError: unorderable types: Foo() < int()
如果我执行 foo.__lt__(1) 我会得到我期望的行为:
In [137]: foo.__lt__(1)
__lt__
Out[137]: NotImplemented
1) 谁能解释一下?
我想编写一个类来捕获所有属性请求(包括函数调用)并在执行它们之前稍微修改请求。本质上,我想编写一个统一修改所有方法(继承的或不存在的)的类,但我不想为每个方法重写重载。我的想法是拦截方法调用,做我的事情,然后继续。
2) 这可以做到吗?
请您参考如下方法:
link ekhumoro 提供了我的问题的答案。为了完整起见,我将在这里总结它们。来自文档:
For custom classes, implicit invocations of special methods are only guaranteed to work correctly if defined on an object’s type, not in the object’s instance dictionary.
虽然这并不能完全解释我的具体情况(在类声明中包含特殊方法将启用隐式功能),但它确实介绍了特殊方法的隐式调用与对象元类(即类型)相关联的想法.这种理解有助于理解下一个片段的含义:
Implicit special method lookup generally also bypasses the
__getattribute__()method even of the object’s metaclass.
因此,特殊方法的隐式调用不使用 __getattribute__类或元类上的方法。换句话说,您不能隐式拦截隐式特殊方法查找。
文档重申了这一结论:
Bypassing the
__getattribute__()machinery in this fashion provides significant scope for speed optimisations within the interpreter, at the cost of some flexibility in the handling of special methods (the special method must be set on the class object itself in order to be consistently invoked by the interpreter).
因此,解决方案是必须在类对象上显式定义特殊方法,以便隐式调用。
在上面的示例中,我明确定义了特殊方法 __lt__在类对象上,因此通过 < 进行隐式调用接线员工作。然而,如前所述,__getattribute__ 都不是由于在解释器中进行了特殊优化,方法(在类或元类上)在过程中被调用。
最后,如果我想创建所需的行为,我需要在我的类对象上显式声明所有受支持的特殊方法。没有 that many of them ,但没有一个简单的“包罗万象”的解决方案。
编辑: 对于那些等待这个故事的结论的人,我找到了一个很好的折衷方案,即在实例化类对象之前以编程方式定义类对象的特殊方法。以下代码片段显示了如何调用 pw函数返回一个特殊对象,该对象拦截指定的运算符并返回一个容器,其中包含对其成员执行的运算符:
def pw(container):
'''Return a PairWise object, which intercepts operations and performs them
on the associated container.'''
# Define the supported functions
# Functions that must return a specific type (i.e. __str__)
# cannot be implemented
funs = ['__lt__','__le__','__eq__','__ne__','__gt__','__ge__']
for f in ['add','sub','mul','truediv', 'floordiv',
'mod', 'divmod', 'pow', 'lshift', 'rshift',
'and','or','xor']:
funs.extend(['__{}__'.format(f), '__r{}__'.format(f)])
for f in ['neg','pos','abs','invert']:
funs.append('__{}__'.format(f))
# Define the pairwise execution wrapper
def pairwise(fun, cont):
def fun2(self, *args, **kwargs):
t = type(cont)
return t(type(c).__getattribute__(c, fun)(*args, **kwargs) \
for c in cont)
return fun2
# Define the PairWise class from the type constructor
# i.e. type(name, bases, dict)
PW = type('PW', (object,),
{fun: pairwise(fun, container) for fun in funs})
# Return an instance of the pairwise class
return PW()
我现在可以通过对 pw 的句法简单调用对容器(列表、集合、元组)执行成对操作:
In [266]: pw([1,2,3,4]) + 1
Out[266]: [2, 3, 4, 5]
In [267]: -pw({7,8,9,10})
Out[267]: {-10, -9, -8, -7}
