This page looks best with JavaScript enabled

Classes and Inheritance in Python

 ·  🎃 kr0m

When a project starts to grow, we are forced to leave the scripting mode of programming and move to a more serious programming mode. I mean, organizing the code using functions with which we can reuse functions, starting to use complex structures which through object-oriented programming will be more comfortable to operate with them. In this article, I will explain briefly how classes work in Python and their inheritance.

In this basic example, we can see how a SysAdmin class inherits from Employee. This way, we will not have to write the Employee code again. The employee2 object will have the methods of Employee by having inherited from this class. I have highlighted the most interesting part of the code in red.

#!/usr/bin/env python

class Employee(object):
  def __init__(self, name, dni):
    self.name = name
    self.dni = dni

  def getName(self):
    return self.name

  def getDni(self):
    return self.dni

class SysAdmin(Employee):
  def __init__(self, name, dni, can_see_matrix):
    Employee.__init__(self, name, dni )
    self.can_see_matrix = can_see_matrix

if __name__ == "__main__":
  employee = Employee('employee00', '123456')
  print "Employee created with following data:"
  print "-- Name: " + str(employee.getName())
  print "-- Dni: " + str(employee.getDni())

  employee2 = SysAdmin('employee01', '54321', 'Sure')
  print "Employee created with following data:"
  print "-- Name: " + str(employee2.getName())
  print "-- Dni: " + str(employee2.getDni())
  print "-- Can See Matrix: " + str(employee2.can_see_matrix)

The SysAdmin class has the methods of Employee thanks to the instruction:

Employee.__init__(self, name, dni )

And the extra parameter can_see_matrix thanks to:

self.can_see_matrix = can_see_matrix
If you liked the article, you can treat me to a RedBull here