What is class and instance attributes in Python?

Class attributes

Class attributes belong to the class itself they will be shared by all the instances. Such attributes are defined in the class body parts usually at the top, for legibility.

In Python, attributes are the variables that hold values associated with an object. There are two types of attributes in Python: class attributes and instance attributes.

Class attributes are the attributes that are shared by all the instances of a class. These attributes are defined inside the class but outside any methods. They are accessed using the class name and can also be modified using the class name. Class attributes are useful for defining properties that are common to all objects of a class.

For example, consider a class called "Person" that has a class attribute "species" with the value "Homo Sapiens". All instances of the Person class will share this attribute. 

In Python, class and instance attributes are used to define variables that are associated with a particular class or instance of that class.

Class attributes are variables that are defined within the class itself and are shared by all instances of that class. They can be accessed using the class name and the dot notation. Class attributes are typically used to store constants or other information that is shared by all instances of the class. For example, a class attribute for a car class might be the number of wheels, which is the same for all cars.

Instance attributes, on the other hand, are variables that are defined within an instance of a class and are unique to that instance. They can be accessed using the instance name and the dot notation. Instance attributes are typically used to store data that is specific to each instance of the class. For example, an instance attribute for a car class might be the color of the car, which can vary from one car to another.

Here's an example of a class and instance attributes in Python: 

 

class Car:
    # Class attribute
    num_wheels = 4
    
    def __init__(self, color):
        # Instance attribute
        self.color = color
        
car1 = Car("red")
car2 = Car("blue")

print(car1.num_wheels)  # Output: 4
print(car2.num_wheels)  # Output: 4

print(car1.color)  # Output: red
print(car2.color)  # Output: blue

In the above example, num_wheels is a class attribute while color is an instance attribute. All instances of the Car class will have the same value for num_wheels, while each instance will have its own unique value for color.

Submit Your Programming Assignment Details