【发布时间】:2010-09-17 10:19:11
【问题描述】:
以下看起来很奇怪.. 基本上,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}
在__init__ 函数中定义self.somedata 显然是解决此问题的正确方法(因此每个类都有自己的somedata dict)-但是什么时候需要这种行为?
【问题讨论】:
标签: python class inheritance