I have come across the notion of class constructors in C++. But I have not yet found a way to initialize a class in Python using 2 or more different methods. Could anyone tell how to go about that?
2 Answers
You don't need multiple constructors in python, you can use the following way to initialize if you have multiple such a case
class A:
def __init__(self, arg_1, arg_2=None):
self.arg_1 = arg_1
self.arg_2 = arg_2
So when you need to initialize an object of class A, you can use
a1 = A(2)
a2 = A(2, 4)
Though strictly speaking __init__ is not a constructor but an initialiser
1 Comment
progmatico
If it is a question of having a few optional arguments, of course this a valid choice. See
help(int.from_bytes) for an example of what I meant in the comment above, giving an alternate method to int()@Ratan Rithwik solution is correct but only only 2 cases
If you want to have as many case as you want, you can use **kwarg
one example with @thebjorn answer
EDIT: mixing 'standard' parameter (having default value) and kwargs
class Player:
def __init__(self, name='John', **kwargs):
self.name = name
self.last_name = kwargs.get('last_name')
p = Player(last_name='Doe')
print (p.name) # John
print (p.last_name) #Doe
p1 = Player('foo')
print (p1.name) # foo
print (p1.last_name) #None
__init__and__new__in the data model google.com/search?client=firefox-b-e&q=python+init+vs+new. Usually in Python you don't implement the constructor (__new__) but just use__init__to initalise a new instance of your class.