Create a list of default objects for a class in Python?

I defined a class in Python

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

I would like to create a list or array of objects of the default class node. For example, something like C ++

node * nodes = node[100];

it nodeswill point to an array of 100 objects of the default class node.

How is this done in Python? Thank.

+4
source share
3 answers

Using list comprehension:

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

You can use understanding:

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

Python does not have the concept of "arrays" as such, but it does have lists that represent a higher level structure. Lists can be indexed just like C arrays, and support many more complex operations .

+5
[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 children list
Out[23]: ['foo']

The right way:

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]: []
+3
source

All Articles