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.
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
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.
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.
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
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.