Class attributes vs instance attributes in Python
Class attributes are the variables defined directly in the class that are shared by all objects of the class.
Instance attributes are attributes or properties attached to an instance of a class. Instance attributes are defined in the constructor.
The following table lists the difference between class attribute and instance attribute:
Class Attribute | Instance Attribute |
---|---|
Defined directly inside a class. | Defined inside a constructor using the self parameter. |
Shared across all objects. | Specific to object. |
Accessed using class name as well as using object with dot notation, e.g. classname.class_attribute or object.class_attribute | Accessed using object dot notation e.g. object.instance_attribute |
Changing value by using classname.class_attribute = value will be reflected to all the objects. | Changing value of instance attribute will not be reflected to other objects. |
The following example demonstrates the use of class attribute count
.
class Student: count = 0 def __init__(self): Student.count += 1
In the above example, count
is an attribute in the Student class. Whenever a new object is created, the value of count
is incremented by 1. You can now access the count
attribute after creating the objects, as shown below.
>>> std1=Student() >>> Student.count 1 >>> std2 = Student() >>> Student.count 2
The following demonstrates the instance attributes.
class Student: def __init__(self, name, age): self.name = name self.age = age
Now, you can specify the values while creating an instance, as shown below.
>>> std = Student('Bill',25) >>> std.name 'Bill' >>> std.age 25 >>> std.name = 'Steve' >>> std.age = 45 >>> std.name 'Steve' >>> std.age 45
Visit Python Class for more information.