使用__getattr__导致TypeError:'str'对象不可调用 - Python 2.7

问题描述 投票:3回答:1

我试图在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获得这种行为?

python python-2.7
1个回答
3
投票

问题是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):
© www.soinside.com 2019 - 2024. All rights reserved.