The Wayback Machine - https://web.archive.org/web/20240829000430/https://www.geeksforgeeks.org/extend-class-method-in-python/
Open In App

Extend Class Method in Python

Last Updated : 06 Feb, 2020
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

In Python, when a subclass defines a function that already exists in its superclass in order to add some other functionality in its own way, the function in the subclass is said to be an extended method and the mechanism is known as extending. It is a way by which Python shows Polymorphism. This is similar to overriding in Java and virtual methods in C++. A call from the instance of the subclass executes the subclass’s version of the function. To call superclass’s version super() method is used.

Why Extend a Function?
The goal of extending a class method in Python can be achieved by Inheritance. One of the major advantages provided by extending a method is that it makes the code reusable. Further, multiple subclasses can share the same code and are even allowed to update it as per the requirement.

We’ll deal with both cases here

CASE 1: without extending a class method




# definition of superclass "Triangles"
class Triangles(object):
      
    count = 0
      
    # Calling Constructor
    def __init__(self, name, s1, s2, s3):
        self.name = name
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
        Triangles.count+= 1
  
    def setName(self, name):
        self.name = name
  
    def setdim(self, s1, s2, s3):
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
  
    def getcount(self):
        return Triangles.count
       
    def __str__(self):
        return 'Name: '+self.name+'\nDimensions: '+str(self.s1)+','+str(self.s2)+','+str(self.s3)
      
      
# describing a subclass 
# inherits from Triangles
class Peri(Triangles):
      
    # function to calculate the area     
    def calculate(self):
        self.pm = 0
        self.pm = self.s1 + self.s2 + self.s3
         
    # function to display just the area 
    # because it is not extended
    def display(self):
        return self.pm
          
      
def main():
      
    # instance of the subclass
    p = Peri('PQR', 2, 3, 4)
    # call to calculate()
    p.calculate()
    # explicit call to __str__()
    print(p.__str__())
    # call to display()
    print(p.display())
      
main()


Output:

Name: PQR
Dimensions: 2, 3, 4
9

CASE 2: extending a class method




# definition of superclass "Triangles"
class Triangles(object):
      
    count = 0
      
    def __init__(self, name, s1, s2, s3):
        self.name = name
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
        Triangles.count+= 1
  
    def setName(self, name):
        self.name = name
  
    def setdim(self, s1, s2, s3):
        self.s1 = s1
        self.s2 = s2
        self.s3 = s3
  
    def getcount(self):
        return Triangles.count
  
    # superclass's version of display()
    def display(self):
        return 'Name: '+self.name+'\nDimensions: '+str(self.s1)+', '+str(self.s2)+', '+str(self.s3)
  
# definition of the subclass
# inherits from "Triangles"
class Peri(Triangles):
          
    def calculate(self):
        self.pm = 0
        self.pm = self.s1 + self.s2 + self.s3
         
    # extended method 
    def display(self):
          
        # calls display() of superclass 
        print (super(Peri, self).display())
          
        # adding its own properties 
        return self.pm
          
      
def main():
      
    # instance of the subclass
    p = Peri('PQR', 2, 3, 4)
      
    # call to calculate
    p.calculate()
      
    # one call is enough 
    print(p.display())
      
main()


Output:

Name: PQR
Dimensions: 2, 3, 4
9

The output produced in both cases is the same, the only difference being that the second case makes it easier for other subclasses to inherit the methods and “extend” them as required which as mentioned increases code reusability.



Similar Reads

Python sympy | sieve.extend() method
With the help of sympy.sieve.extend() method, we can grow the sieve to cover all the prime numbers less than equal to a given natural number. Syntax: sieve.extend(N) Parameter: N - It denotes the number up to which the sieve is extended. Returns: The function does not return anything. Example #1: # import sympy from sympy import sieve # Use sieve.e
1 min read
Python List extend() Method
The Python List extend() method adds items of an iterable (list, tuple, dictionary, etc) at the end of a list. Example C/C++ Code other_cars = ["Maruti", "Tata"] cars.extend(other_cars) print(cars) Output ['Audi', 'BMW', 'Jaguar', 'Maruti', 'Tata']List extend() Syntaxlist_name.extend(iterable) Parameters:iterable: Any iterable (
4 min read
Difference between Append, Extend and Insert in Python
Lists are just like dynamically sized arrays, declared in other languages (vector in C++ and ArrayList in Java). Lists need not be homogeneous always which makes it the most powerful tool in Python. A single list may contain DataTypes like Integers, Strings, as well as Objects. Lists are mutable, and hence, they can be altered even after their crea
3 min read
List Methods in Python | Set 2 (del, remove(), sort(), insert(), pop(), extend()...)
Some of the list methods are mentioned in set 1 below List Methods in Python | Set 1 (in, not in, len(), min(), max()…) More methods are discussed in this article. 1. del[a : b] :- This method deletes all the elements in range starting from index 'a' till 'b' mentioned in arguments. 2. pop() :- This method deletes the element at the position mentio
4 min read
append() and extend() in Python
Extend and Append are two Python list methods used to add elements to a list. Although they appear similar, they have different functionalities and use cases. Understanding the differences between the append() and extend() methods is crucial when working with lists in Python. Although both techniques are used to add elements to a list, their behavi
6 min read
How to Extend User Model in Django
Django’s built-in User model is useful, but it may not always meet your requirements. Fortunately, Django provides a way to extend the User model to add additional fields and methods. In this article, we'll walk through the process of extending the User model by creating a small web project that displays a custom user profile, showcasing the popula
3 min read
Class Method vs Static Method vs Instance Method in Python
Three important types of methods in Python are class methods, static methods, and instance methods. Each serves a distinct purpose and contributes to the overall flexibility and functionality of object-oriented programming in Python. In this article, we will see the difference between class method, static method, and instance method with the help o
5 min read
What is the Proper Way to Call a Parent's Class Method Inside a Class Method?
In object-oriented programming, calling a parent class method inside a class method is a common practice, especially when you want to extend or modify the functionality of an inherited method. This process is known as method overriding. Here's how to properly call a parent class method inside a class method in Python. Basic Syntax Using super()The
3 min read
Call a Class Method From another Class in Python
In object-oriented programming, classes play a pivotal role in organizing and structuring code. Python, being an object-oriented language, allows the creation of classes and their methods to facilitate code modularity and reusability. One common scenario in programming is the need to call a method from one class within another class. In this articl
3 min read
Class method vs Static method in Python
In this article, we will cover the basic difference between the class method vs Static method in Python and when to use the class method and static method in python. What is Class Method in Python? The @classmethod decorator is a built-in function decorator that is an expression that gets evaluated after your function is defined. The result of that
5 min read
Create Derived Class from Base Class Universally in Python
In object-oriented programming, the concept of inheritance allows us to create a new class, known as the derived class, based on an existing class, referred to as the base class. This facilitates code reusability and structuring. Python provides a versatile way to create derived classes from base classes universally, allowing for flexibility and sc
3 min read
Python: Call Parent class method
A class is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Example: # Python program to demonstrate # classes class cls: # Constructor def __init__(self, fname,
4 min read
Isoweekday() Method Of Datetime Class In Python
Isoweekday() is a method of the DateTime class that tells the day of the given date. It returns an integer that corresponds to a particular day. Syntax: datetime.isoweekday() Parameters: None Return Value: It returns an integer which corresponds to a day as per the table Integer ReturnedDay of the week1Monday2Tuesday3Wednesday4Thursday5Friday6Satur
3 min read
Isocalendar() Method Of Datetime Class In Python
The isocalendar() function is used to return a tuple of ISO Year, ISO Week Number, and ISO Weekday. Note: According to ISO standard 8601 and ISO standard 2015, Thursday is the middle day of a week.Therefore, ISO years always start with Monday.ISO year can start as yearly as 29th January or as late as 4th January of a Gregorian calendar.ISO years ca
2 min read
Isoformat() Method Of Datetime Class In Python
In this example, we will learn How to get date values in ISO 8601 format using Python. The Isoformat() function is used to return a string of date, time, and UTC offset to the corresponding time zone in ISO 8601 format. The standard ISO 8601 format is all about date formats for the Gregorian calendar. This format prescribes that a calendar date nee
4 min read
Python program to build flashcard using class in Python
In this article, we will see how to build a flashcard using class in python. A flashcard is a card having information on both sides, which can be used as an aid in memoization. Flashcards usually have a question on one side and an answer on the other. Particularly in this article, we are going to create flashcards that will be having a word and its
2 min read
Difference between Method Overloading and Method Overriding in Python
Method Overloading: Method Overloading is an example of Compile time polymorphism. In this, more than one method of the same class shares the same method name having different signatures. Method overloading is used to add more to the behavior of methods and there is no need of more than one class for method overloading.Note: Python does not support
3 min read
Violinplot in Python using axes class of Matplotlib
Matplotlib is a library in Python and it is numerical - mathematical extension for NumPy library. The Axes Class contains most of the figure elements: Axis, Tick, Line2D, Text, Polygon, etc., and sets the coordinate system. And the instances of Axes supports callbacks through a callbacks attribute. #Sample Code # Implementation of matplotlib functi
2 min read
Matplotlib.ticker.MultipleLocator Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.ticker.MultipleLocator The matplotlib.ticker.MultipleLocator class is used for setting a tick for every integer multiple of a b
1 min read
fromisoformat() Function Of Datetime.date Class In Python
The fromisoformat() function is used to constructs a date object from a specified string that contains a date in ISO format. i.e., yyyy-mm-dd. Syntax: @classmethod fromisoformat(date_string) Parameters: This function accepts a parameter which is illustrated below: date_string: This is the specified ISO format i.e., yyyy-mm-dd date string whose date
2 min read
Matplotlib.gridspec.GridSpec Class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.gridspec.GridSpec The matplotlib.gridspec.GridSpec class is used to specify the geometry of the grid to place a subplot. For th
3 min read
Matplotlib.patches.CirclePolygon class in Python
Matplotlib is an amazing visualization library in Python for 2D plots of arrays. Matplotlib is a multi-platform data visualization library built on NumPy arrays and designed to work with the broader SciPy stack. matplotlib.patches.CirclePolygon The matplotlib.patches.CirclePolygon class is used for polygon-approximation of a circle patch. It is use
3 min read
Python Psycopg - Cursor class
The cursor class Enables Python scripts to use a database session to run PostgreSQL commands. The connection class is what creates cursors. cursor() method: They are permanently connected to the connection, and all instructions are run in the context of the database session covered by the connection. Cursors generated from the same connection aren'
5 min read
Python program to create Bankaccount class with deposit, withdraw function
Prerequisite: Object Oriented Programming in PythonLet's write a simple Python program using OOP concept to perform some simple bank operations like deposit and withdrawal of money.First of all, define class Bankacccount. This step is followed by defining a function using __init__. It is run as soon as an object of a class is instantiated. This __i
2 min read
Python | Avoiding class data shared among the instances
Class attributes belong to the class itself and they will be shared by all the instances and hence contains same value of each instance. Such attributes are defined in the class body parts usually at the top, for legibility. Suppose we have the following code snippet : C/C++ Code # Python code to demonstrate # the working of the sharing # of data v
2 min read
Python Tkinter | Create different type of lines using Canvas class
In Tkinter, Canvas.create_line() method is used to create lines in any canvas. These lines can only be seen on canvas so first, you need to create a Canvas object and later pack it into the main window. Syntax: Canvas.create_line(x1, y1, x2, y2, ...., options = ...) Note: Minimum of 4 points are required to create a line, but you can also add multi
2 min read
Python Tkinter | Create different shapes using Canvas class
In Tkinter, Canvas class is used to create different shapes with the help of some functions which are defined under Canvas class. Any shape that Canvas class creates requires a canvas, so before creating any shapes a Canvas object is required and needs to be packed to the main window. Canvas Methods for shapes: Canvas.create_oval(x1, y1, x2, y2, op
3 min read
How to create a list of object in Python class
We can create a list of objects in Python by appending class instances to the list. By this, every index in the list can point to instance attributes and methods of the class and can access them. If you observe it closely, a list of objects behaves like an array of structures in C. Let's try to understand it better with the help of examples. Exampl
2 min read
rangev2 - A new version of Python range class
range() is a built-in function of Python. It is used when a user needs to perform an action for a specific number of times. The range() function is used to generate a sequence of numbers. But the sequence of numbers produced by range is generally either decreasing or increasing linearly which means it is either incremented and decremented by a part
2 min read
Print objects of a class in Python
An Object is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with actual values. When an object of a class is created, the class is said to be instantiated. All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object.
2 min read
Practice Tags :