This question already has answers here:
Why do attribute references act like this with Python inheritance? [duplicate]
(3个答案)
How to avoid having class data shared among instances?
(7个答案)
6年前关闭。
我不确定此代码的输出是否正确或存在错误:
使用python 2.7.3的输出:
我认为它应该输出:
有什么想法吗?
(3个答案)
How to avoid having class data shared among instances?
(7个答案)
6年前关闭。
我不确定此代码的输出是否正确或存在错误:
class F:
"""An abstract class"""
list_of_secrets = []
def __init__(self):
pass
def getSecret(self):
return self.list_of_secrets
class F_None(F):
pass
class F_Some(F):
def __init__(self):
self.list_of_secrets.append("secret value!")
x = F_Some()
print "x:",x.getSecret()
y = F_None()
print "y:",y.getSecret()
使用python 2.7.3的输出:
x: ['secret value!']
y: ['secret value!']
我认为它应该输出:
x: ['secret value!']
y: []
有什么想法吗?
最佳答案
list_of_secrets
的作用域为此处的类。您想将其附加到self
中的__init__
def __init__(self):
self.list_of_secrets = []