Reputation: 4607
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?
Upvotes: 2
Views: 93
Reputation: 16484
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
Upvotes: 1
Reputation: 81
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
Upvotes: 2
Reputation: 113930
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)
Upvotes: 2