Junior — Middle
How can you distinguish a class variable from an instance variable?
sobes.tech AI
Answer from AI
In Python, variables belonging to a class are called class attributes and are declared inside the class body but outside of methods. They are shared among all instances of the class. Variables associated with a specific object are called instance attributes and are usually created inside methods (for example, in __init__) using self.
Example:
class MyClass:
class_var = 10 # class attribute
def __init__(self, value):
self.instance_var = value # instance attribute
obj1 = MyClass(1)
obj2 = MyClass(2)
print(MyClass.class_var) # 10
print(obj1.class_var) # 10
print(obj1.instance_var) # 1
print(obj2.instance_var) # 2
Thus, the class attribute is accessible via the class name and instances, but is shared among all, while the instance attribute is unique to each object.