当存在uu getattribute和u getattr时,为什么python类示例中会出现“rogue”形状属性?

cmssoen2  于 2021-09-08  发布在  Java
关注(0)|答案(1)|浏览(267)

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

  1. class X:
  2. def __init__(self, count):
  3. self.count = count
  4. x = X(42)

在pycharm调试模式下显示的x结果如下:

  1. x = {X}
  2. count = {int}42

鉴于

  1. class X:
  2. def __init__(self, count):
  3. self.count = count
  4. def __getattribute__(self, item):
  5. # Calling the super class to avoid recursion
  6. return super(X, self).__getattribute__(item)
  7. def __getattr__(self, item):
  8. return self.__setattr__(item, 'fred')
  9. x = X(42)

在pycharm调试模式下显示的x结果如下:

  1. x = {X}
  2. count = {int}42
  3. shape = {str} 'fred'

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

np8igboo

np8igboo1#

简单的答案是 x.__getattr__ 创造 shape 属性,任何人都应该尝试访问它。因为没有现存的 shape 属性 xX , x.shape 通过呼叫解决此问题 x.__getattr__('shape') .
我无法解释是谁(pycharm本身?)试图访问 shape 或者他们为什么会这样做。

相关问题