我的印象是python中任何作为__call__
属性的对象都是可调用的,但事实并非如此。尤其是,似乎不支持在__init__
中设置__call__
,请参见下文。对象的可调用性到底需要什么?为什么这种方法不起作用?在
class A:
def __init__(self):
self.__call__ = self.double
def double(self, x):
"""Doubles `x`."""
return 2 * x
a = A()
try:
print(a(3))
except TypeError as e:
print(e) # 'A' object is not callable
print(a.__call__(3)) # 6
print(a.__call__.__doc__) # 'Doubles `x`.'
以上是我真正的问题,但这是我的动机,以防你有兴趣/认为有更好的方法来实现我的目标。我希望__call__
成为另一个实例方法的包装器,特别是要有相同的docstring。我可以通过以下方式实现:
但问题是,如果我有另一个从B
继承的类,并更改了double
的docstring,那么将使用B.double.__doc__
。在
class B2(B):
def double(self, x):
"""Returns twice `x`."""
return 2 * x
b2 = B2()
print(b2(3)) # 6
print(b2.__call__.__doc__) # 'Doubles `x`.'
这就是为什么我希望在^{__call__
设置为double
会有所帮助。在
目前没有回答
相关问题 更多 >
编程相关推荐