In the world of object-oriented programming (OOP), inheritance refers to the mechanism of a class`s ability to inherit or extend properties of another class at runtime. This property allows a derived class to obtain properties or traits of a base class.
Inheritance in Python is considered one of the most important aspects of OOP because it serves as a reusable function, which makes a piece of code more robust.
< / p>
class SuperClassName: Body of Super class class DerivedClass_Name (SuperClass): Body of de rived class
Let`s dive into the world of Python inheritance with simple examples. Read also about multiple inheritance .
class Father: # The keyword `self` is used to represent the instance of a class. # By using the "self" keyword we access the attributes and methods of the class in python. # The method "__init__" is called as a constructor in object oriented terminology. # This method is called when an object is created from a class. # it allows the class to initialize the attributes of the class. def __init __ (self, name, lastname): self.name = name self.lastname = lastname def printname (self): print (self.name, self.lastname) # Use the Father class to create an object, and then execute the printname method: x = Father ("Anees", "Mulani") x.printname ()
Output: Anees Mulani
# The subclass __init __ () function overrides the inheritance of the base class __init __ () function. class Son (Father): def __init __ (self, name, lastname): Father .__ init __ (self, name, lastname) x = Son ("Dev", "Bajaj") x.printname ()
Conclusion: Dev Bajaj
super () function, you don`t need to use the parent element name, it will automatically inherit the methods and properties from its parent.
class Father: def __init __ (self, name, lastname): self.name = name self.lastname = lastname def printname (self): print (self.name, self.lastname) class Son (Father): def __init __ (self, name, lastname): super () .__ init __ (name, lastname) x = Student ("Dev", "Bajaj") x.printname ()
Become a master in Python by learning coding best practices and advanced programming concepts in Python 3.7. This book is written for Python developers who wish to go further in mastering Python. A...
Computer Age Statistical Inference: Algorithms, Evidence, and Data Science (Institute of Mathematical Statistics Monographs, Series Number 6). The twenty-first century has seen a breathtaking expan...
Mark Lutz is the global leader in Python training, author of the oldest and best-selling Python texts, and a pioneer in the Python community since 1992.
Mark Lutz is the author of the found...
Coding for Kids: Python - Learn to Code with 50 Awesome Games and Activities. Learning to code isn't as difficult as it sounds, you just have to get started! Coding for Kids: Python gets kids start...