Menu

Advanced OOP

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

  1. Read about Abstract Base Classes.
  2. Create a Shape abstract class with an area() method, then implement Circle and Rectangle.
  3. Use @property to add validation to one of your class attributes.

Support me!

I am a software engineer giving back to the community - my name is Musila Peter. Join me in empowering learners around the globe by supporting SaneGenius!