What do? __init__() takes exactly 3 arguments (1 given)? [duplicate] - python

This question already has an answer here:
__init__() takes exactly 3 arguments (1 given)
(1 answer)
Closed 8 years ago.
Here's the error it gives me along with the code lines specified. Apologies for past post.
Traceback (most recent call last):
File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 352, in <module>
main()
File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 346, in main
score = game()
File "H:\Users\Daniel\Desktop\Final Project\Gold Hunter.py", line 195, in game
pirate = Pirate()
TypeError: __init__() takes exactly 3 arguments (1 given)
ACTUAL CODE
main() Line 352
score = game() Line 346
pirate = Pirate() Line 195
Pirate Constructor It gives me the error NameError: global name 'dx' is not defined
class Pirate(pygame.sprite.Sprite):
EAST = 0
def __init__(self, screen, dx):
self.screen = screen
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load("king_pirate/running e0000.bmp")
self.image = self.image.convert()
tranColor = self.image.get_at((1, 1))
self.image.set_colorkey(tranColor)
self.rect = self.image.get_rect()
self.rect.inflate_ip(-50, -30)
self.rect.center = (0, random.randrange(30,450))
self.img = []
self.loadPics()
self.frame = 0
self.delay = 4
self.pause = self.delay
self.dx = dx

I agree with Lee's comment. We cannot see the class Pirate: constructor but it is clear that your __init__ function is taking THREE arguments when you define it. These would be self, argument1, argument2, so when you call pirate = Pirate() on line 195, you must actually provide it 2 arguments (it will get self on its own). You need to give it the argument1 and argument2 that you defined in the constructor. Post the constructor for more help. Your line 195 should look something like pirate = Pirate(argument1, argument2)
Good Luck!

Related

nameerror <function> is not defined error python [duplicate]

This question already has answers here:
How can I call a function within a class?
(2 answers)
Closed 1 year ago.
I am trying to make a program to simulate movement. This is the code
class Object:
forc={}
srtpos = 0
vel = 0
def __init__(self,mass, srtpos = 0):
self.mass = mass
self.srtpos = 0
def UpVel(vel, time = 1, a = 0):
vel1 = vel + a*t
vel = vel1
def Move(self, vel, time = 1, a = 0):
self.srtpos+= self.vel*time +(0.5)*a*(time**2)
UpVel(self.vel, time, a)
a = Object(5)
print(a.srtpos)
for i in range(5):
a.Move(5)
print(a.srtpos)
The UpVel() function is updating the velocity. When i try to run this through the Move() function, the program is giving me error
Traceback (most recent call last):
File "/media/atharva/DATA/Python/PhySim.py", line 17, in <module>
a.Move(5)
File "/media/atharva/DATA/Python/PhySim.py", line 13, in Move
UpVel(self.vel, time, a)
NameError: name 'UpVel' is not defined
I have tried putting the function call in __main__ and also changing the name of the function.
Any help appreciated.
Thanks in advance.
Try to use
self.UpVel(self.vel, time, a)
If you want to use it without self. it needs to be a static method.

Python Inheritance Issue

I have a class that is inheriting from another class, and I get the issue:
Traceback (most recent call last):
File "main.py", line 45, in <module>
class Player(Entity):
File "main.py", line 53, in Player
self.image = pygame.image.load('sam_stand.png')
NameError: name 'self' is not defined
These are the classes:
class RigidBody(object):
def __init__(self, (x, y), size, mass=1):
self.x = x
self.y = y
self.size = size
self.mass = mass
self.thickness = 0
self.angle = 0
self.drag = 1
self.elasticity = 0.9
class Player(Entity):
"""Player class. Provides all player variables and methods"""
def __init__(self):
RigidBody.__init__(self)
self.grounded = True
self.direction = "Right"
self.axis = "Down"
self.jump_counter = 0
self.image = pygame.image.load('sam_stand.png')
How come self is recognized for all the other attributes for the Player, except for self.image? If I change it to image = pygame.image.load('sam_stand.png') the problem goes away.
You are mixing tabs and spaces. When looking at your first revision source I see this:
Your method body is indented with tabs, which Python expands to 8 spaces. The last line, however, is indented with spaces only. You have your editor set to 4 spaces per tab, so you cannot see this mistake.
As a result, the self.image line falls outside the __init__ method. It is part of the class definition instead.
You really want to configure your editor to indent with spaces only.
Run your code with python -tt scriptname.py and fix all the errors that reports. Then run the tabs-to-spaces feature in your text editor (converting to 4 spaces) and then configure it to use spaces for indentation (automatically inserting 4 spaces when you use the tab key).
Using spaces for indentation is recommended by the Python styleguide for a reason, after all.

Pygame: Showing sprite without a group

I have two sprites in a class for easier control (specifically: tank turret and suspension). If I try to launch program it works without any errors, but it doesn’t show anything. I also tried to put both of sprites in group in class, but it threw error
TypeError: draw() missing 1 required positional argument: 'surface'
The code is:
class Bokstelis(pygame.sprite.Sprite):
def __init__(self,atvaizdas,centerx,centery,sukgreitis):
pygame.sprite.Sprite.__init__(self)
self.nuotr=pygame.image.load(atvaizdas)
self.image=self.nuotr
self.rect=self.image.get_rect()
self.rect.centerx=centerx
self.rect.centery=centery
self.sukgreitis=sukgreitis
self.kryptis=0
def update(self):
mouseX, mouseY=pygame.mouse.get_pos()
self.angle = math.degrees(math.atan2(mouseY - self.rect.centery, mouseX - self.rect.centerx))
orig_rect=self.rect
if self.angle - self.kryptis <self.sukgreitis:
self.image=pygame.transform.rotate(self.nuotr,-(self.sukgreitis+self.kryptis))
elif self.angle - self.kryptis >self.sukgreitis:
self.image=pygame.transform.rotate(self.nuotr,self.sukgreitis+self.kryptis)
else:
self.image=pygame.transform.rotate(self.nuotr,-angle)
self.rect=self.image.get_rect()
self.rect.center=orig_rect.center
self.kryptis=self.angle
class Pagrindas(pygame.sprite.Sprite):
def __init__(self,atvaizdas,centerx,centery,sukgreitis):
pygame.sprite.Sprite.__init__(self)
self.nuotr=pygame.image.load(atvaizdas)
self.image=self.nuotr
self.rect=self.image.get_rect()
self.rect.centerx=centerx
self.rect.centery=centery
self.sukgreitis=-sukgreitis
self.kryptis=0
def suktis(self):
orig_rect=self.rect
self.image=pygame.transform.rotate(self.nuotr,-sukgreitis)
self.rect=self.image.get_rect()
self.rect.center=orig_rect.center
self.kryptis-=kryptis
class Tankas:
def __init__(self,centerx,centery,bokstelis,pagrindas,maxjudgreit,galingumas,svoris):
self.bokstelis=bokstelis
self.pagrindas=pagrindas
self.centerx=centerx
self.centery=centery
self.bokstelis.rect.center=(self.centerx,self.centery)
self.pagrindas.rect.center=(self.centerx,self.centery)
self.grup=pygame.sprite.Group(self.bokstelis,self.pagrindas)
self.maxjudgreit=maxjudgreit
self.galing=galingumas
self.svoris=svoris
self.judejimas=0
self.kryptis=self.pagrindas.kryptis
self.greit=False
self.maxdabgreit=72
def update(self):
self.centerx,selfcentery=self.judejimas * math.cos(math.radians(self.kryptis)), self.judejimas * math.sin(math.radians(self.kryptis))
self.bokstelis.rect.center=(self.centerx,self.centery)
self.pagrindas.rect.center=(self.centerx,self.centery)
self.bokstelis.update()
self.pagrindas.update()
if self.maxdabgreit < self.judejimas:
selfjudėjimas-=self.galing/self.svoris
elif self.greit:
self.judejimas=self.judejimasself.galing/self.svoris
For adding class I added 'self.grup(self.bokstelis,self.pagrindas)' in __init__, and changed self.bokstelis.update() and self.pagrindas.update() with
self.grup.clear()
self.grup.update()
self.grup.draw()
Full eror mesage:
Traceback (most recent call last):
File "C:\Users\Kiela\Dropbox\IK8\IK3\World of Tankz.py", line 76, in <module>
tankas.grup.draw()
TypeError: draw() missing 1 required positional argument: 'surface'
What should I do for the displaying of my tank without disabling of my class?
pygame.sprite.Group.draw() requires a non optional argument 'surface'.
If you're bliting straight to the screen (screen = pygame.display.set_mode()) you do: self.grup.draw(screen)
Your other alternative is to make a surface and blit that to the screen:
screen = pygame.display.set_mode((0, 0)) # Create the main window
#Create the sprites and groups etc.
...
surface = pygame.Surface(screen.get_size)
self.grup.draw(surface)
screen.blit(surface)
pygame.display.flip()
but this is the more complicated of the two.
If you want it straight from the docs it can be found here: https://www.pygame.org/docs/ref/sprite.html#pygame.sprite.Group.draw

Python: TypeError: __init__() takes exactly 2 arguments (1 given)

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 code you used is as follows:
player = Player()
This is an issue since the __init__ must be supplied by one parameter called name according to your code. Therefore, to solve your issue, just supply a name to the Player constructor and you are all set:
player = Player('sdfasf')
The problem is that the Class Player's __init__ function accepts a name 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 change
player = Player()
to
player = Player('somename')
to get the program up and running.
__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 of
player = Player()
use
player = Player("George")
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:
class HelloWorld():
def __init__(self):
self.useThis(1)
def useThis(self, useless):
self.useless = useless
print(useless)
# Run class
HelloWorld()
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:
self.exampleOne()
self.exampleTwo('input1', 'input2')

Python code returning syntax error on "if self.hp < 0" line

I've been following along with this series of youtube videos in order to get a more hands on approach to python. I don't have a deep understanding of what some of the code does, but I more or less get what each piece is supposed to achieve, even though I may not be sure how.
I'm getting a Syntax error on the last line here:
class Character(object):
def __init__(self, name, hp):
self.name = name
self.hp = hp
self.dead = False
def attack(self, other):
pass
def update(self):
if self.hp < 0 #Error's on this line
self.dead = True
self.hp = 0
Here is the traceback:
Traceback (most recent call last): File "game.py", line 4, in
<module>
from Characters.player import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/player.py", line 2,
in <module>
from character import * File "/Users/Devlin/Desktop/Dev/Python/rpg/Characters/character.py", line
12
if self.hp < 0
^ SyntaxError: invalid syntax
You forgot a colon (:) at the end of the line:
if hp < 0:
Your init also looks like a constructor. As such, it should likely be __init__ instead of init. Otherwise, you're going to run into problems with it not being executed at object instantiation.

Categories

Resources