Python: Class Inheritance and Compositions

Inheritance 

A Derived class inherits from a Base class and is a specialized version of Base. It allows defining a class that inherits all the methods and properties of another class.

The syntax for a subclass definition looks like this:

class DerivedClassName(BaseClassName):
    pass

Super() function will make the child class inherit all the methods and properties from its parent:

Example:

import json

class Pet:
    def __init__(self, name):
        self.name = name

class Dog(Pet):
    def __init__ (self, name, breed=None):
        super().__init__(name)
        self.breed = breed

    def say_hi(self):
        return f"Hi {self.name}"

class ExportJson:
    def to_json(self):
        return json.dumps({
            "name": self.name
            "breed": self.breed
            })

class ExDog(Dog, ExportJson):
    pass

Pet is a Base Class, Dog – is a subclass of Pet Class, ExDog – a subclass of multiple classes: Dog and ExportJson.

Each class is a subclass of class “object”. To check the subclass of the class: issubclass

Check an instance of the class: isinstance

Method Resolution Order – the order of the classes Python is looking for attributes or method: __mro__

Composition

If we have another class that needs to be added, we will have to extend the ExDog class each time. It’s better to pass it as the attribute:

class Pet – name
class Dog – breed
class ExDog – exporter
as a result: instance dog will have a name (from Pet), a breed (from Dog) and exporter function passed to the ExDog class (None as default, but using ExportJson if export() method is used)

Share

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *