使用python class变量的风险

class Parent(object):
    x = 1
class Child1(Parent):
    pass
class Child2(Parent):
    pass

print Parent.x, Child1.x, Child2.x
# 1 1 1

Child1.x = 2
print Parent.x, Child1.x, Child2.x
# 1 2 1

Parent.x = 3
print Parent.x, Child1.x, Child2.x
# 3 2 3

这段代码重点在第三次print结果“3 2 3”

当子类没有重新设置父类的变量时,会直接使用父类的变量,所以当父类变量发生变化时,Child2也发生变化。

我们可以用下面代码列出类的属性

print ', '.join(['%s:%s' % item for item in Child2.__dict__.items()])

 输出:

“Child2 __module__:__main__, __doc__:None”

可以看出里面是没有属性“x”的。所以会引用父类的x值。

对于并发运行多个子类的场景,子类使用class变量有可能导致value传递到其它子类。所以我们要明确在子类使用前对变量进行初始化。

猜你喜欢

转载自heipark.iteye.com/blog/2344830
今日推荐