- Do you always have to use
__init__
as constructor? - How many constructors can you use it in one class?
- Do you need to have 'self' as first argument or you can use any other name like 'shapes' instead of 'self'?
Asked
Active
Viewed 82 times
0

Martijn Pieters
- 1,048,767
- 296
- 4,058
- 3,343

Bharath Kashyap
- 343
- 2
- 5
- 14
-
6Please 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 Answers
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?). - One, called
__init__
(though it can call out to other functions). - No, but using a name other than
self
will make your code harder to read by others, who expect the nameself
by convention.

Colonel Thirty Two
- 23,953
- 8
- 45
- 85
-
1: *No*, unless you want to have Python let you know a new instance has been created and want to do something with that instance when it just has been created. Like setting initial values for attributes. – Martijn Pieters Jan 27 '15 at 19:17
-
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.