Class Attributes vs Instance Attributes in Python

preview_player
Показать описание
#pyhton #oop #objectorientedprogramming
In this lecture, we'll be diving into class attributes and understanding how they differ from instance attributes.
We'll also cover all the ways to access class attributes and demonstrate how they can be useful when working with multiple objects that share common properties.
Let's start by defining what a class attribute is.
Class attributes are variables that are shared by all instances of a class.
This means that every object created from the class will have access to the same value for these attributes unless we explicitly change it for a specific instance.
Let's start a fresh example to explore this.
In this file, let's define the Car class with a class attribute 'number_of_wheels':
The __init__ function is the same as before and isn't actually relevant for this example.
In this case, 'number_of_wheels' is a class attribute that is shared by all instances of Car.
Now, let's create two car objects.
Next, we'll explore the ways to access class attributes.
In Python, there are two main ways to do this.
The first way is to access the class attribute directly from the class itself.
Let's print the number of wheels directly from the class.
The second way is to access the class attribute through an instance of the class.
This time, we print the number of wheels for each car using their instances.
When we run this script,
The output shows that both the class and the instances reflect the same value for the 'number_of_wheels' attribute, confirming that it is shared across all objects of the Car class.
This demonstrates how class attributes provide a single source of truth for properties common to all instances.
Now, what happens if we change the class attribute?
If you modify the class attribute via the class itself, it will automatically update for all instances.
Let's see how this works in practice.
As you can see, modifying the class attribute through the class changes it for all instances.
But what if we want to change the class attribute for just one specific object?
If you modify the class attribute through an instance, the change will apply only to that particular instance, leaving others unaffected.
Here's what happens when we do that.
Now, car1 has its own value for 'number_of_wheels', while car2 still uses the class attribute value.
To summarize, in this lecture, we explored class attributes and how they differ from instance attributes.
We learned that class attributes are shared by all instances of a class and can be accessed or modified in two ways.
We also saw how class attributes can be overridden for individual instances.
Class attributes are useful when objects need to share common properties that rarely change.