首页 > 解决方案 > 当 __getattribute__ 和 __getattr__ 存在时,为什么 Python 类实例中会出现“流氓”形状属性?

问题描述

我试图了解 dunder getattributegetattr方法的功能。在进行实验时,我注意到课堂上出现了一个意想不到的形状属性。我找不到任何解释为什么会发生这种情况。

class X:
    def __init__(self, count):
        self.count = count

x = X(42)

结果 x 在 PyCharm 调试模式下显示为:

x = {X}
  count = {int}42

然而

class X:
    def __init__(self, count):
        self.count = count

    def __getattribute__(self, item):
        # Calling the super class to avoid recursion
        return super(X, self).__getattribute__(item)

    def __getattr__(self, item):
        return self.__setattr__(item, 'fred')

x = X(42)

结果 x 在 PyCharm 调试模式下显示为:

x = {X}
  count = {int}42
  shape = {str} 'fred'

属性“形状”从何而来,它的用途是什么?

标签: pythongetattrgetattribute

解决方案


简单的答案是,如果任何人尝试访问它,x.__getattr__ 就会创建该属性。因为or上shape没有现有shape属性,所以通过调用.xXx.shapex.__getattr__('shape')

我无法解释谁(PyCharm 本身?)试图访问shape或他们为什么会这样做。


推荐阅读