Quick Enquiry Form

×

    EnquiryEnquire Now

    Quick Enquiry

      Method Overloading in Python

      Method Overloading in Python
      Blog Cloud Computing

      Method Overloading in Python

      Method overloading means creating various methods with the same name using different types or parameters. In this case, the method will perform multiple functionalities with the same name. Method overloading is one of the primary concepts in object-oriented programming in Python. In this article, we explain method overloading in Python in detail, along with examples and tested codes to run for your practice.

      How is Method Overloading in Python Possible?

      In general, Python doesn’t support method overloading. Though it doesn’t show any compile-time errors, the method overloading in Python will be considered using the last defined method. If we try to call the overloaded method using various arguments or parameters, then we get errors at runtime.  Here is an example of creating a class using various methods with the same name but different parameters. 

      class mtdovl:

          def Welcome(self, name= None):

              if name is not None:

                  print(‘Welcome’ + name)

              else:

                  print(‘Welcome’)

      obj = mtdovl() # Create an instance

      obj.Welcome() # Call the method

      obj.Welcome(‘ to SLA’) # Call the method with a parameter

      Method overloading allows us to invoke the Welcome method in the code above in two distinct ways. Introduction to Python is a beginner’s guide that helps you understand the Python programming language from scratch.

      Now, let’s see another example

      class Calc:

          def add(self, x, y):

            print(“x + y = {}”.format(x + y))

          def add(self, x, y, z):

            print(“x + y + z = {}”.format(x + y + z))

      zz = Calc()

      zz.add(4, 2, 3)

      zz.add(4,2)

      As you can see from the example above, we built a class that has two overloaded methods—one with two parameters and the other with three. Subsequently, we generated an instance for the Calc class and invoked the add function with various arguments.

      Do you want to learn about the key differences between Python 2 and Python 3? Check out our recent article.

      The following is the outcome that you will obtain when you run the Python method overloading example mentioned before.

      Traceback (most recent call last):

        File “./prog.py”, line 8, in <module>

      TypeError: add() missing 1 required positional argument: ‘z’

      The add method is expecting another parameter, as you can see by looking at the result above. Python, as was mentioned, only takes into account the most recent specified method.

      Get practiced with the frequently asked Python interview questions and answers here.

      Implementation of Method Overloading in Python

      We must write methods that use default arguments or variable-length arguments to achieve method overloading in Python.

      Method Overloading in Python using Default Arguments

      class Calc:

         def add(self, x, y, z = 0):

           if z > 0:

               print(“x + y + z = {}”.format(x + y + z))

           else:

               print(“x + y = {}”.format(x + y))

      zz = Calc()

      zz.add(4, 2, 5)

      zz.add(4,2)

      As you can see, we use different arguments to invoke the same method (add) in the example above. The output displayed below is what you will get when you run the overloading example Python method mentioned above.

      x + y + z = 11

      x + y = 6

      If you are not aware of jump statements in Python yet, learn about them in our article.

      Method Overloading in Python using Variable Length Arguments

      As was previously mentioned, method overloading in Python can be accomplished by using variable-length arguments in the method. You can call a method with a different number of parameters if you create one with variables for the length of the arguments.

      Here’s an example of how to accomplish method overloading in Python by developing a method with variable-length arguments.

      class Calc:

         def add(self, *args):

           result = 10

           for parameter in args:

              result += parameter

              print(“Result: {}”.format(result))

      n1 = Calc()

      n1.add(100, 200, 300)

      n1.add(100,200)

      The overloading example in Python above will yield the following result.

      Result: 110

      Result: 310

      Result: 610

      Result: 110

      Result: 310

      This is how, depending on your needs, you can accomplish method overloading in Python. 

      Building web applications with Django is simple now. Explore how.

      Advantages of Method Overloading in Python

      Method overloading in Python helps in

      • Reduced complexities
      • Improved quality of the code
      • Utilized for reusability
      • Easy to access

      Bottom Line

      We hope this method overloading in Python helps you understand how you can accomplish overloading methods using default arguments and variable-length arguments. 

      Explore all the opportunities in Python by enrolling in our basic to advanced level Python training in Chennai at SLA Jobs.

      For Online & Offline Training

      Have Queries? Ask our Experts

      +91 88707 67784 Available 24x7 for your queries

      Quick Enquiry Form

        1
        Softlogic-Academy