繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM