Overloading constructors in python

Constructor overloading in Python | Example code

Constructor overloading means more than one constructor in a class with the same name but a different argument (parameter). Python does not support Constructor overloading; it has no form of function.

In Python, Methods are defined solely by their name, and there can be only one method per class with a given name.

Example constructor overloading in Python

Simple example code to achieve constructor overloading based on args.

class Example: # constructor overloading based on args def __init__(self, *args): # if args are more than 1 sum of args if len(args) > 1: self.answer = 0 for i in args: self.answer += i # if arg is an integer square the arg elif isinstance(args[0], int): self.answer = args[0] * args[0] # if arg is string Print with hello elif isinstance(args[0], str): self.answer = "Hello! " + args[0] + "." e1 = Example(1, 2, 3, 6, 8) print("Sum :", e1.answer) e2 = Example(6) print("Square :", e2.answer) e3 = Example("Python") print("String :", e3.answer) 

Constructor overloading in Python

Constructor overloading in python with default arguments

Python does not support multiple constructors. However, you can emulate them easily as follows:

class MyClass: def __init__(self, edate=None, fdate=""): if edate: print("Constructors", edate) else: print("Default Constructor") obj1 = MyClass("01-Dec-2021") obj2 = MyClass() 

Constructors 01-Dec-2021
Default Constructor

Читайте также:  Container shadow in css

How to overload __init__ method based on argument type?

Answer: Do get ‘alternate constructors’ is to use classmethods. For instance:

class MyData: def __init__(self, data): self.data = data @classmethod def fromfilename(cls, filename): data = open(filename).readlines() return cls(data) @classmethod def fromdict(cls, datadict): MyData([1, 2, 3]).data return cls(datadict.items()) print(MyData.fromfilename("file.txt").data) print(MyData.fromdict().data) 
[‘Welcome Developer’]dict_items([(‘spam’, ‘ham’)])

Source: stackoverflow.com/

Do comment if you have any doubts or suggestions on this Python constructor tutorial.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Источник

Overload a Constructor in Python

Overload a Constructor in Python

  1. Using Multiple Arguments to Overload Constructors in Python
  2. Use the @classmethod Decorators to Overload a Constructor in Python

Multiple constructors help in customizing our custom class accordingly to its parameters. While using different parameters, we can trigger different constructors.

Multiple constructors are not directly supported in Python. When multiple constructors are provided in the class, the latest one overrides the previous one. But there are some alternative ways to overload a constructor in Python.

We will discuss these methods in this article.

Using Multiple Arguments to Overload Constructors in Python

Function overloading refers to having different functions with the same name with different types of parameters. We can overload a constructor by declaring multiple conditions, with every condition based on a different set of arguments.

class delftstack:  def __init__(self, *args):  if isinstance(args[0], int):  self.ans = args[0]  elif isinstance(args[0], str):  self.ans = "Hello from "+args[0]  s1 = delftstack(1) print(s1.ans)  s2 = delftstack("Delft") print(s2.ans) 

In the above example, we have two types of parameters in the constructor. One is a string, and the other is an integer. The construct is overloaded to give the output based on the type of arguments provided.

We can also overload a constructor based on the number of arguments provided. This method is similar to the previous example.

class delftstack:  def __init__(self, *args):  if len(args)>3:  self.ans = "More than three"  elif len(args)3:  self.ans = "Less than three"  s1 = delftstack(1,2,3,4) print(s1.ans)  s2 = delftstack(1,2) print(s2.ans) 
More than three  Less than three 

Use the @classmethod Decorators to Overload a Constructor in Python

The @classmethod decorator allows the function to be accessible without instantiating a class. Such methods can be accessed by the class itself and via its instances. When used in overloading, such functions are called factory methods. We can use them to implement the concept of constructor overloading in Python.

class delftstack(object):  def __init__(self, a):  self.ans = 'a'   @classmethod  def first(cls):  return "first"   @classmethod  def second(cls):  return "second"  s1 = delftstack.first()  print(s1)  s2 = delftstack.second()  print(s2) 

This method is the most pythonic way of overloading a constructor. In the above example, the cls argument of the factory method refers to the class itself.

Related Article — Python Constructor

Copyright © 2023. All right reserved

Источник

Ways to Achieve Multiple Constructors in Python

python multiple constructors

Hello Programmers, today’s article is about multiple constructors in Python. Switching to python from any other programming language has all advantages except when it comes to multiple constructors. Python does not support multiple constructors. However, python offers some of the alternative ways to support multiple constructors. We will discuss some of those ways here. But before that let me brief you about what is the need for multiple constructors in a program.

Multiple constructions help you to customize your class according to its parameters. Upon using a different number of parameters, different constructions can be triggered. Unlike other programming languages, Python has a different way of handling multiple parameters. We’ll have a look at each of them in detail.

Python Multiple Constructors And Its Need:

Multiple constructors come to use when a defined class has to perform different functions. And on different parameters or instances of a class.

On writing the same method multiple times for a class, the last one overwrites all the previous constructors. Since multiple constructors do not work well with python, the class constructors exhibit polymorphism. This method helps to replicate the multiple constructor feature in python.

Different ways to get Multiple Constructors in Python are:

  • Constructor overloading based on arguments
  • Methods calling from __init__
  • @classmethod decorator

Python Constructor overloading based on arguments as Multiple Constructors:

class eaxmple: # constructor overloading # based on args def __init__(self, *args): # if args are more than 1 # sum of args if len(args) > 1: self.answer = 0 for i in args: self.answer += i # if arg is an integer # square the arg elif isinstance(args[0], integer): self.answer = args[0]*args[0] # if arg is string # Print with hello elif isinstance(args[0], str): self.answer = "Hello! "+args[0]+"." e1 = example(1, 2, 3, 6, 8) print("Sum of list :", e1.answer) e2 = example(6) print("Square of integer :", e2.answer) e3 = example("Programmers") print("String :", e3.answer)
Sum of list : 20 Square of integer : 36 String : Hello! Programmers

EXPLANATION:

In the above example, the answer is the instance variable of the class example. Its value differed in different instances inside the class based on arguments. A class can have multiple arguments. Therefore *args is defined as a tuple that holds different arguments passed to it. The arguments are accessible using an index. For instance, as in the integer and string case, since only one argument is passed, it is thus accessed as args[0]. While for the sum, more than one argument passed to it is accessed by using a loop.

Python Methods calling from __init__ as Multiple Constructors:

class equations: # single constructor to call other methods def __init__(self, *abc): # when 2 arguments are passed if len(abc) == 2: self.ans = self.eq1(abc) # when 3 arguments are passed elif len(abc) == 3: self.ans = self.eq2(abc) # when more than 3 arguments are passed else: self.ans = self.eq3(abc) def eq1(self, args): x = (args[0]*args[0])+(args[1]*args[1]) return y def eq2(self, args): y = args[0]+args[1]-args[2] return x def eq3(self, args): temp = 0 for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/5.0 z = temp return z abc1 = equations(4, 2) abc2 = equations(4, 2, 3) abc3 = equations(1, 2, 3, 4, 5) print("equation 1 :", abc1.ans) print("equation 2 :", abc2.ans) print("equation 3 :", abc3.ans)
equation 1 : 12 equation 2 : 17 equation 3 : 11.0

EXPLANATION:

In this example, three equations performed in the instances of the class are : equaton1 – x= a 2 + b 2 equation2 – y = a + b – c. Equation3 – z = sum of the square of arguments passed / 5.0.

equation1 is for two arguments. equation2 is for three and equation 3 for more than three.

Using a multi constructor in python, a class having one constructor __init__ is defined. It can perform any action on the creation of different class instances. Above all, in the above code, equations to be evaluated are written in different instances of the class. Above all the __init__ constructor calls different methods to return the answer based on the number of arguments passed.

@classmethod decorator as Multiple Constructors:

class equations: # basic constructor def __init__(self, x): self.ans = x @classmethod def eq1(obj, args): # create an object for the class to return a = obj((args[0]*args[0])+(args[1]*args[1]) return a @classmethod def eq2(obj, args): b = obj(args[0]+ args[1] - args[2]) return b @classmethod def eq3(obj, args): temp = 0 # square of each element for i in range(0, len(args)): temp += args[i]*args[i] temp = temp/5.0 z = obj(temp) return z li = [[4, 2], [4, 2, 3], [1, 2, 3, 4, 5]] i = 0 # loop to get input three times while i < 3: input = li[i] # no.of.arguments = 2 if len(input) == 2: p = equations.eq1(input) print("equation 1 :", p.ans) # no.of.arguments = 3 elif len(input) == 3: p = equations.eq1(input) print("equation 2 :", p.ans) # More than three arguments else: p = equations.eq3(input) print("equation 3 :", p.ans) #increment loop i += 1
equation 1 : 12 equation 2 : 17 equation 3 : 11.0

EXPLANATION:

Equations performed in the above example are: equaton1 – x= a 2 + b 2 . Equation2 – y = a+ b – c. Similarly Equation3 – z = sum of the square of arguments passed / 5.0.

When two arguments are passed, equation1 is evaluated. For three arguments, equation2 is performed. And for more than three arguments, equation3 is evaluated.

Instances are not created for the above class initially. Similarly, class methods are defined to evaluate the various equations using the @classmethod decorator. Therefore they are now called using class names. In addition, we create objects inside the class methods itself after the evaluation of the equations. Therefore the instance variable returns the answer.

Must Read

Conclusion:

In conclusion, we can say, Python itself can not support the use of multi constructors for a class. It allows different alternatives discussed above. However, constructor overloading and __init__ definition incurs certain problems. Firstly, there is no clear indication of what is required while creating class instances. Also, there are different combinations of initializing a new instance by passing arguments. The best out of the three alternatives given is thus decorating with @classmethod decorators as multi constructors.

However, if you have any doubts or questions do let me know in the comment section below. I will try to help you as soon as possible.

Happy Pythoning!

Источник

Оцените статью