最近在接触 Python 类的概念时,我发现了这个观察结果并且无法理解。
当我尝试以交互方式(Python 控制台)从下面的类中创建实例时,我也得到了Finding __len__
输出中的行。
class MyClass(object):
counter = 0
data = 'Class Variable'
def __init__(self):
self.counter += 1
self.value = -1
def __str__(self):
return "Instance {} is the {} instance".format(self.__class__.__name__, self.counter)
def __getattr__(self, item):
print(f'Finding {item}')
return self.__dict__.get(item, f'Attr {item} not available, {self.__dict__}')
def __setattr__(self, key, value):
if key not in self.__dict__:
self.__dict__[key] = value
def __delattr__(self, item):
print(f'Deleting attr: {item}')
if item in self.__dict__:
del self.__dict__[item]
else:
print(f'Cannot find {item} in {self.__dict__}')
if __name__ == '__main__':
inst = MyClass()
print(inst.id)
但是将其作为顶级模块运行,不会在输出中添加此附加行。
有人可以帮我理解,为什么Finding __len__
输出会以交互方式显示。
下面是一个交互式输出,
import WS1
x = WS1.MyClass()
Finding __len__
x.name = 'Yathin'
Finding __len__