Skip to content Skip to sidebar Skip to footer

Difference Between Instance Attributes And Class Attributes

I'm trying to learn about the instance and class attributes in python. Then am a little confused: is this_obj.var an instance attribute or it belongs to the class attribute. The c

Solution 1:

Instance and class attributes can be kind of confusing to understand at first. The best way of thinking about it is to pay attention to the name.

Instance attributes are owned by the specific instance of the class, meaning that these attributes can vary from instance to instance of a specific class.

On the other hand, Class attributes are owned by the class itself, so the attribute has the same value for each instance of a particular class.

In your example, var would be a class attribute to every instance of MyClass. However, once var is set to a different value for any given instance, say this_obj.var = 69, then this_obj.var is now an instance attribute to the this_obj instance. Meaning, instance attribute are created upon changing the class attribute of any instance.

Hope that helps!

EDIT: You can also change the class attribute value itself, meaning it'll change for all instances without an instance attribute for that specific variable. For example MyClass.var = 34 would change the value for all instances of MyClass that hasn't created an instance attribute yet.

Post a Comment for "Difference Between Instance Attributes And Class Attributes"