-
Notifications
You must be signed in to change notification settings - Fork 0
Decorators
Three main decorators will be looked into:
- @property
- @classmethod
- @staticmethod
The code, which will be used to demonstrate all of them is here and certain sections will be pasted below for illustration.
This decorator is used in the class to instantiate properties of the class. Since the class is a Circle, one of the properties is a radius and the other is an area.
Click to expand the code!
@property
def radius(self):
"""Get value of radius"""
return self._radius
@radius.setter
def radius(self, value):
"""Set radius, raise error if negative"""
if value >= 0:
self._radius = value
else:
raise ValueError("Radius must be positive")
@property
def area(self):
"""Calculate area inside circle"""
return self.pi() * self.radius**2The radius of a circle must be given to calculate the area, however, one cannot set the area of a circle without the radius. Therefore, the radius is a property of the class circle.
As the radius can have a value, it will be set with a setter method of the property decorator, in our case @radius.setter. More info on the getter, setter, & deleter methods of property here.
Note, how the radius method needs to have the same name for setting the @radius.setter. If we were to use the getter & deleter methods for the radius they would have the same method name as setter.
The area doesn't need to be set and therefore doesn't have a setter method like radius.