python - 当 __getattribute__ 和 __getattr__ 存在时,为什么 Python 类实例中会出现“流氓”形状属性?
问题描述
我试图了解 dunder getattribute和getattr方法的功能。在进行实验时,我注意到课堂上出现了一个意想不到的形状属性。我找不到任何解释为什么会发生这种情况。
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'
属性“形状”从何而来,它的用途是什么?
解决方案
简单的答案是,如果任何人尝试访问它,x.__getattr__
就会创建该属性。因为or上shape
没有现有shape
属性,所以通过调用.x
X
x.shape
x.__getattr__('shape')
我无法解释谁(PyCharm 本身?)试图访问shape
或他们为什么会这样做。
推荐阅读
- ios - 快速:collectionView 部分
- python - 如何获取字符串上的所有子字符串(用户输入)
- android - NestedScrollview + Coordinator Layout + SmartTabLayout 具有带有片段的 viewpager 滚动无限问题
- jquery - 猫头鹰旋转木马没有按预期工作
- ios - 插座已连接,但在展开可选值时意外发现 nil
- python - 仅考虑第一个匹配项 (Python Re)
- java - 氧气 IDE 未启动
- java - 没有获取系统类的 setProperty 方法
- java - 错误:任务“:app:processDebugResources”执行失败。> 错误:多个库的包名称为“android.support.graphics.drawable”
- ios - 摆脱重复项目的最快方法?