Basic inheritance

suggest change

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):
    pass

class DerivedClass(BaseClass):
    pass

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:

r.area()
# Output: 12
r.perimeter()  
# Output: 14

s.area()
# Output: 4
s.perimeter()
# 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

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Classes:
* Basic inheritance
*

Table Of Contents
2 Filter
3 List
7 Loops
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve