I noticed that in Python, people initialize their class attributes in two different ways.
The first way is like this:
class MyClass:
__element1 = 123
__element2 = "this is Africa"
def __init__(self):
#pass or something else
The other style looks like:
class MyClass:
def __init__(self):
self.__element1 = 123
self.__element2 = "this is Africa"
Which is the correct way to initialize class attributes?
Neither way is necessarily correct or incorrect, they are just two different kinds of class elements:
__init__method are static elements; they belong to the class.__init__method are elements of the object (self); they don’t belong to the class.You’ll see it more clearly with some code:
As you can see, when we changed the class element, it changed for both objects. But, when we changed the object element, the other object remained unchanged.