[英]Pickle of object with __getattr__ method in Python returns `TypeError, object not callable`
[英]Use of __getattr__ results in TypeError: 'str' object is not callable - Python 2.7
我试图在Python 2.7中定义一个简单的类和实例,但是我遇到了__getattr__的问题。 下面的最小工作示例:
class MyClass:
def __init__(self,value):
self.a = value
def __getattr__(self,name):
return 'hello'
class MyOtherClass:
def __init__(self,value):
self.a = value
MyInstance = MyClass(6)
MyOtherInstance = MyOtherClass(6)
现在,如果我输入dir(MyInstance)
我会得到:
TypeError: 'str' object is not callable
但如果我输入dir(MyOtherInstance)
我会得到:
['__doc__', '__init__', '__module__', 'a']
同样,如果我输入MyInstance
我会得到:
TypeError: 'str' object is not callable
但如果我进入MyOtherInstance
我会得到:
<__main__.MyOtherClass instance at 0x0000000003458648>
MyOtherInstance
的行为是我所期望的。 为什么我没有使用MyInstance
获得此行为?
问题是MyClass
是一个旧式类(即,它没有显式地从object
或另一个新式类继承),这意味着__getattr__
被用于不触发对新的__getattr__
调用的魔术方法式班。
要查看此内容,请将您的课程更改为
class MyClass:
def __init__(self,value):
self.a = value
def __getattr__(self,name):
print("Looking up %s" % (name,))
return 'hello'
使用MyInstance
会触发对MyInstance.__repr__
的调用,但是__repr__
计算字符串'hello'
,而不是类的__repr__
方法。
>>> MyInstance
Looking up __repr__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
类似地, dir(MyInstance)
触发对MyClass.__dir__
的调用,而__dir__
同样是字符串'hello'
,而不是适当的方法。
>>> dir(MyInstance)
Looking up __dir__
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' object is not callable
您没有MyOtherClass
的相同问题,因为您没有覆盖__getattr__
。
从object
继承会使问题消失; 在回退到__getattr__
之前,会单独查找魔术方法。
class MyClass(object):
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.