2

I was trying to implement method overloading in Python, so I create a Class named Tes where I have two variables, one is va, other is vb.

class Tes:
    def __init__(self,a,b):
        self.va=a
        self.vb=b
        print(self.va)
        print(self.vb)
    def __init__(self,a):
        self.__init__(a,"b-default")

Tes("n1","n2")
Tes("n3")

But it gives me error in Tes("n1","n2"),saying : Tes("n1","n2") TypeError: __init__() takes 2 positional arguments but 3 were given

How to implement constructor overloading correctly in python?

3 Answers 3

2

I guess you are asking this

class Tes:
    def __init__(self,a,b="default_value_b"):
        self.va=a
        self.vb=b
        print(self.va)
        print(self.vb)
Sign up to request clarification or add additional context in comments.

1 Comment

I can accept your answer in 2 minutes, till then can you take a look at - stackoverflow.com/questions/59232341/…
2

You can only use overriding, rather than overloading.
This way may be useful.

def __init__(self, a, b="some value"):
    self.va = a
    self.vb = b
    # do something

Comments

1

How to implement constructor overloading correctly in python?

Python does NOT support any constructor or function overloading. However, it doesn't need to. Instead, it supports setting default parameters.

class Tes:
    def __init__(self, a, b="default_value_b"):
        self.va = a
        self.vb = b
        print(self.va)
        print(self.vb)

The question changes a little if you are using typing. Typing is a relatively new to Python and purely optional. Typing allows you to statically validate your code against expectations, and it can ease writing code by providing live assistance.

In your simple case, you would not use overloading, because it only defines an optional parameter. The type of the parameter stays the same regardless. With Mypy type annotations, your code can be written as follows:


class Tes:
  def __init__(self, a: str, b: str = "default value for b") -> None:
    self.va = a
    self.vb = b
    print(self.va)
    print(self.vb)

If you want to allow None as a value for b, change the signature to:

def __init__(self, a: str, b: Optional[str] = "default value for b") -> None:

Optional can be imported from typing:

from typing import Optional

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.