Python: Extending a Class

By Xah Lee. Date: .

Extending a Class, Inheritance

A class can be extended. If a class B extends class A, then class B automatically have all the attributes (the variable and functions) of A.

# example of extending a class. inheritance

class Dog:
    "A class example"

    def bark(self):
        return "woof"

# extend a class, by putting the base class in the parameter.
class Puppy(Dog):
    "Puppy extends Dog"

    def cute(self):
        return True

# create a object of Puppy
xx = Puppy()

# bark is from Dog. a inherited method
print(xx.bark())
# woof

Multiple Inheritance

python allow multiple inheritance.

# example of multiple inheritance


class Dog:
    def legs(self):
        return 4

class Bird:
    def wings(self):
        return 2

class FlyingDog(Dog, Bird):
    def is_monster(self):
        return True

xx = FlyingDog()

print(xx.wings() == 2)
# True
print(xx.legs() == 4)
# True
print(xx.is_monster() == True)
# True

Method Resolution Order in Multiple Inheritance

You can use the magic attribute __mro__ to list Method Resolution Order.

It returns a tuple of classes in the order of method resolution.

Mro stands for Method Resolution Order.

# example of using __mro__ to show Method Resolution Order.

class Dog:
    def legs(self):
        return 4

class Bird:
    def wings(self):
        return 2

class FlyingDog(Dog, Bird):
    def is_monster(self):
        return True

print(FlyingDog.__mro__)
# (<class '__main__.FlyingDog'>, <class '__main__.Dog'>, <class '__main__.Bird'>, <class 'object'>)

Python. Class and Object