Python初始化类中的列表 [英] Python's initialization a list in a class
问题描述
我不了解python的行为,我有很多相同的错误:
I don't understand python's behavior, I've got many the same errors:
print2中的文件"./start.py",第20行,
item.print2()
RuntimeError:超过最大递归深度
File "./start.py", line 20, in print2
item.print2()
RuntimeError: maximum recursion depth exceeded
我的代码如下:
#!/usr/bin/python
class Component:
def print2(self):
pass
class Composite(Component):
items = []
name = 'composite'
def __init__(self, name):
self.name = name
def add(self, item):
self.items.append(item)
def print2(self):
if self.items:
for item in self.items:
item.print2()
else:
print self.name
class Leaf(Component):
name = 'leaf'
def __init__(self, name):
self.name = name
def print2(self):
print self.name
category = Composite('category1')
leaf = Composite('leaf1')
category.add(leaf)
leaf = Leaf('leaf2')
category.add(leaf)
category.print2()
当我在构造函数( __ init __
)中添加 self.items = []
时,它可以正常工作.您能解释一下这种行为吗?
When I add self.items = []
in the constructor ( __init__
), it works fine. Could you explain the behavior?
推荐答案
items
是一个类变量,因此它由 Composite
的每个实例共享.当您将 append
附加到 items
中时,所有实例都会获得该项目.因此,添加 leaf
后,您将拥有:
items
is a class variable, so it is shared by every instance of Composite
. When you append
into items
, all instances get that item. So after adding the leaf
s, you have:
Type Composite.items
------------------------------------------
Composite category1 [leaf1, leaf2]
|
Composite leaf1 [leaf1, leaf2]
|
Leaf leaf2
如果在 leaf1
上调用了 print2
,它将尝试在其中的每个 items
上调用 print2
该类,它一次又一次地无限次地包含 leaf1
.
If print2
is called on leaf1
, it will try to call print2
on each of the items
in the class, which includes leaf1
again, and again, in an infinite recursion.
如果您在 __ init __
内部初始化 self.items = []
,它将是一个实例变量而不是类变量,因此每个 Composite
将具有其自己的 items
列表.
If you instead initialize self.items = []
inside __init__
, it will be an instance variable instead of a class variable, so each Composite
will have its own list of items
.
这篇关于Python初始化类中的列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!