Python class variable definition difference

Question:

Is there a difference between these 2 Python classes?

class MyItem
    children = []

and

class MyItem
    def __init__(self):
        self.children = []

I can’t seem to find an answer. Note that same class is initiated several times.

Asked By: tilz0R

||

Answers:

For the first one, the attribute will be static. It means that it will be the same for every object create with this class. If you modify it in one object, it will be modified for everyone.
For the second one, the attribute will be linked to the object

Answered By: Nicolas

In the first version, children is a class variable. It is attached to the class itself and can be accessed as MyItem.children. In the second version, children is attached to a specific instance of the class. Each instance has a separate list.

Answered By: Unmitigated
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.