我试图在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):