python发生继承时 __dict__属性
class LazyDB(): def __init__(self, exist=6) -> None: self.exists=exist print('Initilized called') # def __getattr__(self, name): # value='V for %s'%name # self.__dict__[name]=value # return value class LoggingLazyDB(LazyDB): def __getattr__(self, name): value='Child V for %s'%name self.__dict__[name]=value print('father __dict__', super().__dict__) return value data2 = LoggingLazyDB() data2.foo print('After child:', data2.__dict__)
输出:
Initilized called
father __dict__ {'exists': 6, 'foo': 'Child V for foo'}
After child: {'exists': 6, 'foo': 'Child V for foo'}
可以看出继承时子类实例中的__dict__属性其实和父类共用,子类改变后父类也改变,这和一些博客宣称的不同

浙公网安备 33010602011771号