在Python中创建一个类的默认对象列表?

时间:2014-08-21 22:21:50

标签: python

我在Python中定义了一个类

class node(object):
    def __init__(self, children = []):
        self.children = children

我想创建类node的默认对象的列表或数组。例如,类似于C ++

node * nodes = node[100];

然后nodes将指向包含类node的100个默认对象的数组。

在Python中它是如何完成的?感谢。

3 个答案:

答案 0 :(得分:7)

使用列表理解:

nodes = [node() for _ in range(100)]

答案 1 :(得分:5)

您可以使用list comprehension

nodes = [node() for _ in range(100)]

Python本身没有“数组”的概念,但它有一个更高级别的结构列表。列表可以像C数组一样索引,support many more complex operations

答案 2 :(得分:3)

[node() for _ in range(100)]

正如我在评论中所说:

class node(object):
    def __init__(self, children=None):
        if children is None: children = []
        self.children = children

如果您使用def __init__(self, children= []):,则您对列表所做的任何更改都将针对所有实例进行更改:

In [18]: class node(object):
   ....:     def __init__(self, children = []):
   ....:            self.children = children
   ....:         

In [19]: n1= node()

In [20]: n2 = node()

In [21]: n1.children.append("foo") # add using n1 

In [22]: n1.children
Out[22]: ['foo']

In [23]: n2.children # also effects n2's children list
Out[23]: ['foo']

正确的方式:

In [24]: class node(object):
   ....:     def __init__(self, children=None):
   ....:            if children is None: children = []
   ....:            self.children = children
   ....:         

In [25]: n1= node()

In [26]: n2 = node()

In [27]: n1.children.append("foo")

In [28]: n1.children
Out[28]: ['foo']

In [29]: n2.children
Out[29]: []