以下看起来很奇怪.. 基本上, somedata 属性似乎在继承自的所有类之间共享the_base_class
。
class the_base_class:
somedata = {}
somedata['was_false_in_base'] = False
class subclassthing(the_base_class):
def __init__(self):
print self.somedata
first = subclassthing()
{'was_false_in_base': False}
first.somedata['was_false_in_base'] = True
second = subclassthing()
{'was_false_in_base': True}
>>> del first
>>> del second
>>> third = subclassthing()
{'was_false_in_base': True}
self.somedata
在函数中定义__init__
显然是解决这个问题的正确方法(所以每个类都有自己的somedata
dict)——但是什么时候需要这种行为呢?