0

I have been learning some basics of OOP in Python and I found that it does not allow multiple constructors on it. However, I have tried the following code:

class Whatever:

    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y

    def Whatever(self,x,y):
        self.x=x
        self.y=y   

and when I execute it, this works just as multiple constructors:

c=Whatever()
print c.x,c.y
0,0
d=Whatever(1,2)
print d.x,d.y
1,2

is this fine to build multiple constructors in Python?

Little
  • 3,363
  • 10
  • 45
  • 74
  • 1
    This will work as well even if you remove `Whatever` method. – awesoon Sep 03 '14 at 02:26
  • I suppose he obvious question is: why? Why do you need multiple constructors? One of the reasons people ask for this is because they come from another language, like C++, where this practice is common. Usually the requirements can be met by using sensible default parameters. – cdarke Sep 03 '14 at 03:51

1 Answers1

3

Your second "constructor" is actually never called. The __init__ function is being called when you call Whatever both with and without arguments; calling Whatever(1,2) simply calls __init__ with x=1 and y=2.

The Whatever function you added will not behave the way you want if you do call it, because it's an instance method; you'd need to already have a Whatever instance created to call it. You want a classmethod instead:

class Whatever(object):

    def __init__(self,x=0,y=0):
        self.x=x
        self.y=y

    @classmethod
    def Whatever(cls,x,y):
        return cls(x,y)

d = Whatever.Whatever(1, 2)

But this is really unnecessary, since __init__ covers both ways you want to initialize your class.

dano
  • 91,354
  • 19
  • 222
  • 219