Consider that you want to build a city and theme of the city colour blue, you can rather choose to paint different colour to paint and you will decide which house get which colour rather than you choose to colour whole city blue.
And it just like that class variable is one variable can apply to whole function used in class.
class Car: total_car=0 def __init__(self,brand,model): self.brand=brand self.model=model Car.total_car+=1 def full_function(self): return f"{self.brand} {self.model}" def fuel_type(self): return "Petrol or Desiel" class ElectricCar(Car): def __init__(self,brand,model,battery_size): super().__init__(brand,model) self.battery_size=battery_size def fuel_type(self): return "Electric Charge" Tata=Car("TATA","Sedan") Mahindera=Car("Mahindera","Geep") Tesla=ElectricCar("Tesla","ModelX","85KWH") print(Car.total_car)
Output: 3
- In this class, total_car is used as a class variable to keep track of the total number of cars. It is shared across all instances of the class.
- Although total_car should be accessed using the class name (e.g., Car.total_car), it is technically possible to access or even assign it through an instance (e.g., tata.total_car).
- However, if you assign a value to total_car using an instance (like tata.total_car = 5), it doesn't modify the shared class variable. Instead, it creates a new instance variable named total_car, shadowing the class variable. This can lead to unexpected or incorrect behavior, often referred to as a "garbage value" in this context.
Top comments (0)