
If a subclass try to inherits methods or data from another subclass then it will through an error as we see when Dog class try to call swatstring() methods from that cat class, it throws an error(like AttributeError in our case). In the above example, we see the command attributes or methods we put in the parent class so that all subclasses or child classes will inherits that property from the parent class. In Python, constructor of class used to create an object (instance), and assign the value for the attributes.Ĭonstructor of subclasses always called to a constructor of parent class to initialize value for the attributes in the parent class, then it start assign value for its attributes. Let’s create couple of classes to participate in examples − Let’s take a closure look into the inheritance example −

Because of that when we try to get the get_date method from the Time class object tm we created earlier possible. Through this call we get access to all the data and attributes of Date class into the Time class. Later we created another class called time and called the Date class as an argument. We first created a class called Date and pass the object as an argument, here-object is built-in class provided by Python. Private data fields and methods are accessible only inside the class. One point to note here is that only data fields and method which are not private are accessible by child classes. In object-oriented terminology when class X extend class Y, then Y is called super/parent/base class and X is called subclass/child/derived class.

Later you can add you own methods and data fields, thus inheritance provides a way to organize code, rather than rewriting it from scratch. Using inheritance you can use or inherit all the data fields and methods available in your base class. It allows programmer to write better code. Inheritance allows programmer to create a general or a base class first and then later extend it to more specialized class. Inheritance is one of the mechanisms to achieve the same. One of the major advantages of Object Oriented Programming is re-use. You must understand it better if you want to learn. Inheritance and polymorphism – this is a very important concept in Python.
