recyclesite.blogg.se

Python oop inheritance example
Python oop inheritance example










  • The dispSides() method displays these side lengthsĪ triangle is a polygon with 3 sides.
  • The inputSides() method takes in the magnitude of each side.
  • This class has data attributes to store the number of sides n and magnitude of each side as a list called sides. Say, we have a class called Polygon defined as follows, class Polygon: Let's take a look at another example of inheritance in Python,Ī polygon is a closed figure with 3 or more sides. Here, Car can inherit from Vehicle, Apple can inherit from Fruit, and so on. That is, we use inheritance only if there exists an is-a relationship between two classes. In Python, inheritance is an is-a relationship. This is possible because the subclass inherits all attributes and methods of the superclass.Īlso, we have accessed the name attribute inside the method of the Dog class using self. Here, we are using labrador (object of Dog) to access name and eat() of the Animal class. Notice the statements, labrador.name = "Rohu" In the above example, we have derived a subclass Dog from a superclass Animal. # access name attribute of superclass using self

    python oop inheritance example

    # attribute and method of the parent class Here, we are inheriting the sub_class class from the super_class class.Įxample 1: Python Inheritance class Animal: Here's the syntax of the inheritance in Python, # define a superclass

    python oop inheritance example

    The new class that is created is known as subclass (child or derived class) and the existing class from which the child class is derived is known as superclass (parent or base class).

    python oop inheritance example

    Inheritance allows us to create a new class from an existing class. Like any other OOP languages, Python also supports the concept of class inheritance.












    Python oop inheritance example