Introduction
Now that you understand the basics of classes, let's explore more advanced OOP concepts: properties, class methods, static methods, abstract classes, and composition.
Properties and encapsulation
class Temperature:
def __init__(self, celsius=0):
self._celsius = celsius
@property
def celsius(self):
return self._celsius
@celsius.setter
def celsius(self, value):
if value < -273.15:
raise ValueError("Temperature below absolute zero!")
self._celsius = value
@property
def fahrenheit(self):
return self._celsius * 9/5 + 32
temp = Temperature(100)
print(temp.fahrenheit) # 212.0
temp.celsius = -300 # ValueError!Class and static methods
class Pizza:
def __init__(self, ingredients):
self.ingredients = ingredients
@classmethod
def margherita(cls):
return cls(["mozzarella", "tomatoes"])
@classmethod
def pepperoni(cls):
return cls(["mozzarella", "pepperoni"])
@staticmethod
def validate_topping(topping):
return topping in ["mozzarella", "tomatoes", "pepperoni", "mushrooms"]
p = Pizza.margherita() # Factory method
print(p.ingredients) # ["mozzarella", "tomatoes"]Assignment
- Read about Abstract Base Classes.
- Create a
Shapeabstract class with anarea()method, then implementCircleandRectangle. - Use
@propertyto add validation to one of your class attributes.