我正在尝试理解dunder 和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'“形状”属性从何而来?它的目的是什么?
发布于 2021-07-09 14:49:54
简单的答案是,如果有人试图访问shape属性,那么shape就创建它。因为x或X上都没有存在的x.shape属性,所以通过调用x.__getattr__('shape')来解析x.shape。
我无法解释谁(PyCharm本身?)尝试访问shape,或者为什么要这样做。
https://stackoverflow.com/questions/68318637
复制相似问题