Sobes.tech
Junior — Middle

What is the difference between declaring a variable inside a constructor and declaring a variable at the class level?

sobes.tech AI

Answer from AI

Declaring a variable inside a constructor and at the class level in Python differs in scope and lifetime:

  • Class-level variable — this is a class attribute, shared among all instances. It is created once and accessible through the class and all its objects.

  • Variable inside the constructor (usually via self) — this is an instance attribute, unique to each object of the class.

Example:

class MyClass:
    class_var = 10  # class variable

    def __init__(self, value):
        self.instance_var = value  # instance variable

obj1 = MyClass(5)
obj2 = MyClass(7)

print(obj1.class_var)      # 10
print(obj2.class_var)      # 10
print(obj1.instance_var)   # 5
print(obj2.instance_var)   # 7

Thus, changing class_var will affect all objects, while changing instance_var affects only the specific instance.