Python Language Classes Basic inheritance

Help us to keep this website almost Ad Free! It takes only 10 seconds of your time:
> Step 1: Go view our video on YouTube: EF Core Bulk Extensions
> Step 2: And Like the video. BONUS: You can also share it!


Inheritance in Python is based on similar ideas used in other object oriented languages like Java, C++ etc. A new class can be derived from an existing class as follows.

class BaseClass(object):

class DerivedClass(BaseClass):

The BaseClass is the already existing (parent) class, and the DerivedClass is the new (child) class that inherits (or subclasses) attributes from BaseClass. Note: As of Python 2.2, all classes implicitly inherit from the object class, which is the base class for all built-in types.

We define a parent Rectangle class in the example below, which implicitly inherits from object:

class Rectangle():
    def __init__(self, w, h):
        self.w = w
        self.h = h
    def area(self):
        return self.w * self.h
    def perimeter(self):
        return 2 * (self.w + self.h)

The Rectangle class can be used as a base class for defining a Square class, as a square is a special case of rectangle.

class Square(Rectangle):
    def __init__(self, s):
        # call parent constructor, w and h are both s
        super(Square, self).__init__(s, s)
        self.s = s

The Square class will automatically inherit all attributes of the Rectangle class as well as the object class. super() is used to call the __init__() method of Rectangle class, essentially calling any overridden method of the base class. Note: in Python 3, super() does not require arguments.

Derived class objects can access and modify the attributes of its base classes:

# Output: 12
# Output: 14

# Output: 4
# Output: 8

Built-in functions that work with inheritance

issubclass(DerivedClass, BaseClass): returns True if DerivedClass is a subclass of the BaseClass

isinstance(s, Class): returns True if s is an instance of Class or any of the derived classes of Class

# subclass check        
issubclass(Square, Rectangle)
# Output: True

# instantiate
r = Rectangle(3, 4)
s = Square(2)

isinstance(r, Rectangle)  
# Output: True
isinstance(r, Square)
# Output: False
# A rectangle is not a square

isinstance(s, Rectangle)
# Output: True
# A square is a rectangle
isinstance(s, Square)
# Output: True

Got any Python Language Question?