Reputation: 4007
Let’s code for example a class called Rocket
:
class Rocket():
def __init__(self, name):
print("Created a Rocket called '" + str(name) + "'!")
def liftOff(self):
print("10, 9 ,8 ,7 ... Lift Off!!")
and create an instance SaturnV
of this class, but pass no arguments to the __init__
method:
SaturnV = Rocket()
We produce a TypeError
:
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
SaturnV = Rocket()
TypeError: __init__() takes exactly 2 arguments (1 given)
Why does the compiler print, that __init__()
takes exactly 2 arguments instead of 1 required name
argument?
Why do they not change the error message to something like...
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
SaturnV = Rocket()
TypeError: __init__() takes exactly 1 argument in addition to the instance reference (0
arguments given)
Upvotes: 1
Views: 2578
Reputation: 3094
Python counts the self
keyword as an argument as well. That just means that it expects to be called on an class instance via the famous .
(as in satrurnV.name
)or you could optionally do a getattr(saturnV, "name")
to retrieve the same thing.
The __init__()
method is special because it gets called implicitly when you do Rocket()
which is basically Rocket.__init__()
. Now you see that the other argument, the one that you're missing is the name
.
you also have an error in your code:
print("Created a Rocket called" + "'str(name)'" + "!")
should be
print("Created a Rocket called" + str(name) + "!")
str()
function takes the object in the ()
and returns a string so there's no need to ut that under " "
Upvotes: 1