gpt4 book ai didi

python - Python 中的实例变量不像我想象的那样

转载 作者:行者123 更新时间:2023-11-28 19:40:25 24 4
gpt4 key购买 nike

我在 Python 中遇到了一个我不敢相信会发现的问题。见以下代码:

class Container(object):
array = []

def __init__(self):
print self.array

for i in range(0, 5):
container = Container()
container.array.append('Test')
print 'Last Container:', container.array

输出是:

[]
['Test']
['Test', 'Test']
['Test', 'Test', 'Test']
['Test', 'Test', 'Test', 'Test']
Last Container: ['Test', 'Test', 'Test', 'Test', 'Test']

我认为 Container 类在实例化时使用顶部的值进行了初始化。为什么不是这样?

谢谢!

最佳答案

class: 中的代码在创建类时执行,而不是在创建类实例时执行。这是一个更清楚地说明这一点的示例:

>>> class Test(object):
... print "Test"
... def __init__(self):
... print "init"
...
Test
>>> t = Test()
init

请注意,“Test”是在创建类时打印的,而不是在我创建 Test 对象时打印的。

正如其他答案所指出的,如果您希望某个属性对于类的特定实例(而不是类的所有实例)是本地的,则必须将代码放在 __init__ 方法:

def __init__(self):
self.array = []

关于python - Python 中的实例变量不像我想象的那样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10970878/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com