I know this question has been asked several times, but none have managed to provide me with a solution to my issue. I read these:
__init__() takes exactly 2 arguments (1 given)?
class __init__() takes exactly 2 arguments (1 given)
All I am trying to do is create two classes for a "survival game" much like a very crappy version of minecraft. Bellow is the full code for the two classes:
class Player:
'''
Actions directly relating to the player/character.
'''
def __init__(self, name):
self.name = name
self.health = 10
self.shelter = False
def eat(self, food):
self.food = Food
if (food == 'apple'):
Food().apple()
elif (food == 'pork'):
Food().pork()
elif (food == 'beef'):
Food().beef()
elif (food == 'stew'):
Food().stew()
class Food:
'''
Available foods and their properties.
'''
player = Player()
def __init__(self):
useless = 1
Amount.apple = 0
Amount.pork = 0
Amount.beef = 0
Amount.stew = 0
class Amount:
def apple(self):
player.health += 10
def pork(self):
player.health += 20
def beef(self):
player.health += 30
def stew(self):
player.health += 25
And now for the full error:
Traceback (most recent call last):
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 26, in <module>
class Food:
File "/home/promitheas/Desktop/programming/python/pygame/Survive/survive_classe s.py", line 30, in Food
player = Player()
TypeError: __init__() takes exactly 2 arguments (1 given)
I just want to make the classes work.
The problem is that the Class
Player
's__init__
function accepts aname
argument while you are initializing the Class instance. The first argument,self
is automatically handled when you create a class instance. So you have to changeto
to get the program up and running.
The code you used is as follows:
This is an issue since the
__init__
must be supplied by one parameter calledname
according to your code. Therefore, to solve your issue, just supply a name to the Player constructor and you are all set:__init__()
is the function called when the class is instantiated. So, any arguments required by__init__
need to be passed when creating an instance. So, instead ofuse
The first argument is the implicit
self
, which doesn't need to be included when instantiating.name
, however, is required. You were getting the error because you weren't including it.Your code know expects that you input something in
__init__
which you don't.I have made a simple example below that does give you an idea where the error
__init__() takes exactly 2 arguments (1 given)
is coming from.What I did is I made a definition where I give input to
useless
.And I am calling that definition from
__init__
.Example code:
If you have a definition like
def exampleOne(self)
it doesn't expect any input. It just looks a t itself.But
def exampleTwo(self, hello, world)
expects two inputs.So to call these two you need: