Fist thing,
What is Decorators?
In Python, a decorators is a special type of function that modifies or enhances the behaviour of another function or method without changing its actual code.
Here is an analogy:-
Imagine you have a gift, let say a book. To make it special you wrap up with gift paper. Just like decorators.
Here is the problem when I change the model name of our car attribute it get change but it shouldn't be happened:-
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" @staticmethod def general_description(): return "Cars mean of transportation" 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") Tata.model="city" print(Tata.model)
Output: city
As you can see I can change model name how avoid this situation and make model read-only.
We are going to use property method. What property method going to do is that having control over attribute so nobody can have access of it.
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" @staticmethod def general_description(): return "Cars mean of transportation" @property def model(self): return self.__model 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") Tata.model="city" print(Tata.model)
Output: ERROR! Traceback (most recent call last): File "", line 26, in File "", line 5, in __init__ AttributeError: property 'model' of 'Car' object has no setter
- You need private the model attribute.
- Use property method to have access of an attribute so nobody can modify it.
- It also says you cannot even modify with function (model()).
- After erasing Tata.model="city" then only you can have access to it.
Top comments (0)