python __getattr__ 和 __name__

标签 python

我在 Python 2.6 中使用“新样式”类,但在子类中使用 __getattr__ 时遇到问题。

如果子类实现这样的...

def __getattr__(self, name):
    if self.__folderDict.has_key(name):
        if name == 'created':
            return doSomethingSpecial(self.__folderDict[name])
        return self.__folderDict[name]
    else:
        raise AttributeError()

我不清楚为什么我的属性异常会因对 __name__ 的引用而抛出?

我的理解是 __getattr__ 甚至不应该被调用,并且 __name__ 应该由 __getattribute__ 填充,因为我使用的是新样式?

这是一个更完整的示例...

class Base(object):
    @staticmethod
    def printMsg(msg, var):
        print msg + str(var)
        return

    def printName(self):
        Base.printMsg('#', self.__name__)
        return

class Derived(Base):
    def __getattr__(self, name):
        if self.__testDict.has_key(name):
            return self.__testDict[name]
        else:
            raise AttributeError()

    __testDict = {'userid': 4098}


d = Derived()
print d.userid
d.printName()

结果是...

4098
Traceback (most recent call last):
File "D:/.../Scratch/scratch01.py", line 24, in <module>
d.printName()
File "D:/.../Scratch/scratch01.py", line 17, in __getattr__
raise AttributeError()
AttributeError

最佳答案

__name__ 是为类对象预定义的,而不是实例,并且在尝试读取它之前,您不会在任何地方定义 __name__ 。因此 _getattr__ 被调用(因为 __name__ 无法通过正常查找找到)并导致异常。我怀疑你真正想要的是:

...
def printName(self):
    Base.printMsg('#', self.__class__.__name__)
    return
...

关于python __getattr__ 和 __name__,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9751339/

相关文章:

Python - tkinter Treeview 不更新整数变量

python - 使用带有错误 ='replace' 的 str.decode 仍然会出现错误

python - 从一维 numpy 数组中有效地切片窗口,围绕第二个二维数组给出的索引

.net - 绘制曲线和创建 JPEG 的最佳平台

python - 类变量对于 list 和 int 的行为不同?

python - 需要转换 ASN1(x509) 的帮助

python - objects.all() 查询不起作用

python - 如何格式化 CSV 中的字典列表? - Python

python - Azure Blob - 使用 Python 读取

python - 如何在 TensorFlow 中评估 MNIST 测试数据期间从每个输出节点获取值?