0
  1. Do you always have to use __init__ as constructor?
  2. How many constructors can you use it in one class?
  3. Do you need to have 'self' as first argument or you can use any other name like 'shapes' instead of 'self'?
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
Bharath Kashyap
  • 343
  • 2
  • 5
  • 14
  • 6
    Please keep it to one question per post. I believe that there are duplicate questions for each of your individual queries. – Martijn Pieters Jan 27 '15 at 19:15
  • 1
    `__init__` is actually an instance's initializer, it's optional, but can't be given a different name. In Python the constructor is called `__new__`. There's a default one, so again it's optional, however if you provide one it must use that name in order to override the default one. The first argument to the initializer can be named anything, but the instance being initialized will always be passed as the first argument whatever you choose to call it (so it's not optional). – martineau Jan 27 '15 at 19:30

2 Answers2

1
  1. The constructor is optional. However, if you specify one, it must be named __init__; it cannot be named anything else (otherwise, how would Python know which function is the constructor?).
  2. One, called __init__ (though it can call out to other functions).
  3. No, but using a name other than self will make your code harder to read by others, who expect the name self by convention.
Colonel Thirty Two
  • 23,953
  • 8
  • 45
  • 85
1

The one and only constructor for initializing an instance is __init__. If you want polymorphism, you simply have to be flexible about the way you parse and interpret __init__'s input arguments. Do you have to use it? No, you can omit it, in which case Python calls the __init__ method of the superclass, if any.

There is also a method called __new__, called before __init__, but it is intended for a different purpose and behaves differently: see https://stackoverflow.com/a/674369/3019689

And no, self can be renamed but the result will be less-readable, less-maintainable code since self is the well-established conventional name.

Community
  • 1
  • 1
jez
  • 14,867
  • 5
  • 37
  • 64