Python 3: object() takes no parameter [closed] - python

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I have a class inside a file called Weapons.py called Pistol that looks like this:
class Pistol(object):
MAXAMMO = 6
def __init__(self, ammo):
if(ammo <= self.MAXAMMO):
self.ammo = ammo
def shoot(self):
if(ammo > 0):
accuracy = random.randint(0, 3)
return 3 * accuracy
ammo -= 1
else:
print("No ammo")
And a class called ColtM1911 that inherits from Pistol. It looks like this:
class ColtM1911(Pistol):
MAXAMMO = 7
def __init__(self, ammo):
self.ammo = 7
When I run:
import Player
import SetUp
from Utils import *
import pickle
import TitleAnimation
import os
import SaveLoad
from Weapons import *
gun = ColtM1911(5)
In another file it gives me "TypeError: object() takes no parameters" When trying this in the shell it worked, so I suspect it is to do with having it in a separate file.
The full traceback is,
Traceback (most recent call last):
File "C:\Users\James\Documents\game.py", line 3, in <module>
gun = Weapons.ColtM1911(5)
TypeError: object() takes no parameters

The only way I can recreate your error is if Pistol is actually defined as:
class Pistol(object()):
# ^ note extraneous parentheses
In Python 3.x, you don't need object at all; all classes are new-style by default. Also, there are logic errors and M1911.__init__ is redundant. Try something like:
import random
class Pistol:
MAXAMMO = 6
def __init__(self, ammo):
if ammo <= self.MAXAMMO:
self.ammo = ammo
else:
# what do you want do do here? Raise an error? Set ammo = MAXAMMO?
def shoot(self):
if self.ammo > 0:
self.ammo -= 1
return 3 * random.randint(0, 3)
else:
print("No ammo")
class ColtM1911(Pistol):
MAXAMMO = 7

Related

TypeError: 'int' object is not callable - Python beginner [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 11 months ago.
Improve this question
I'm a fairly new programmer and I started learning Python. I've given myself the task of programming a text-based RPG with a kind of round-based fighting like Pokémon or the older Final Fantasy games. Right now I'm working on the battle mechanics, but I ran into an error which I couldn't fix. When I call the 'battle' function in my main I always get the error: 'TypeError: 'int' object is not callable'. I'd be happy if you could help me with this one, like I said, I'm still very new to programming.
My error-Message:
Traceback (most recent call last): File "C:\Doku\Python310\Scripts\text_adventure.py", line 169, in <module>
battle(main.health, main.attack, main.defence, enemy.health, enemy.attack, enemy.defence, main, enemy) File "C:\Doku\Python310\Scripts\text_adventure.py", line 106, in battle
x = player.attack(enemy.health) TypeError: 'int' object is not callable
line 169
#call battle function with the stats of my main character and an enemy
battle(main.health, main.attack, main.defence, enemy.health, enemy.attack, enemy.defence, main, enemy)
line 103-112
#choose between attack and special attack - error occurs with both descisions the same way
while True:
desc = choose()
if desc == 'A' or desc == 'a':
x = player.attack(enemy)
y = player.check_battle()
break
elif desc == 'B' or desc == 'b':
player.specialmove(enemy)
player.check_battle()
break
my choose function:
#couldn't run it without it, don't know why
def choose():
desc = input()
return desc
my main (shortened)character class:
class Main:
#init
def __init__(self, Mhealth, Mattack, Mdefence):
self.health = Mhealth
self.attack = Mattack
self.defence = Mdefence
self.multiplier = 1.00
#attacks
def attack(self, enemy):
x = enemy.health - (self.attack-enemy.defence)
enemy.setHealth(x)
def specialmove(self, enemy):
enemy.health -= round((self.attack*1.5)-enemy.defence)
def movelist(self):
moves = ['A - Attack', 'B - Special']
return moves
my enemy class is built the same way
self.attack is an integer. You set it in __init__ part of the class. Rename either the attack function or this number.

Python - mesa : How to get instance variables of each object [duplicate]

This question already has an answer here:
Python- how to get list of self variables in a class consist of N-self
(1 answer)
Closed 6 years ago.
I am using mesa for my program. I am trying to execute my Model Class, but I got AttributeError from the Agent Class.
This is my script:
class ComtrModel (Model):
""" A model with some number of Agents"""
def __init__(self,N):
self.num_agents = N
self.schedule = RandomActivation(self)
for i in range (N):
a = CommuterAgent(i)
self.schedule.add(a)
class CommuterAgent (Agent):
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
def step(self):
if self.distance >= 10000:
self.update_need = self.update_need()
return
def update_need (self, famsize):
if self.famsize :
self.famsize = famsize
return
prob_need()
How to get variables of each agent? I need to check it to make sure the model run properly.
So far this is my code to execute (on interactive session):
from src.ComtrModel import *
model = ComtrModel(5)
for i in range (10):
model.step()
for key, value in CommuterAgent.step(model):
print(key, value)
EDIT : But it returns
Traceback (most recent call last):
File "C:src/__init__.py", line 3, in <module>
from src.ComtrModel import *
File "C:\src\__init__.py", line 9, in <module>
for key, value in CommuterAgent.step(model):
File "C:\src\ComtrModel.py", line 40, in step
if self.distance >= 10000:
AttributeError: 'ComtrModel' object has no attribute 'distance'
I also have tried something like this:
>>> hi_obj = hi()
>>> hi_obj.__dict__.keys()
But it only works for single object
def __init__(self, model):
self.famsize = famsize
self.distance = distance
self.update_need = None
Doesn't look correct. You don't pass famsize and distance as parameters.

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 3.3 Class method not working, why? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 8 years ago.
Improve this question
Hi below is the relevant code for my problem:
class Player:
def __init__(self, name, x, y, isEvil):
self.health = 50
self.attack = randint(1, 5)
self.name = name
self.x = x
self.y = y
self.isEvil = isEvil
def checkIsAlive(self):
if self.health <= 0:
return False
else:
return True
# implicit in heritance. if the child doesn't have a function that the parent has
# the functions of the parent can be called as if it were being called on the
# parent itself
class Enemy(Player):
#def __init__(self, name, x, y, isEvil):
# self.health = 50
# self.name = name
# self.x = x
# self.y = y
pass
and a little more code:
e = Enemy('Goblin', 10, 11, True)
p = Player('Timmeh', 0, 1, False)
isLight()
while True:
if p.checkIsAlive() == True and e.checkIsALive() == True:
fight()
else:
if p.checkIsAlive() == True:
print('%s is victorious!!! %s survived with %s health points.' % (p.name, p.name, p.health))
else:
print('%s shrieks in its bloodlust!!! %s has %s health points' % (e.name, e.name, e.health))
however when i try and run this I get the following error:
Traceback (most recent call last):
File "<string>", line 420, in run_nodebug
File "C:\Python33\practice programs\textstrat\classees.py", line 94, in <module>
if p.checkIsAlive() == True and e.checkIsALive() == True:
AttributeError: 'Player' object has no attribute 'checkIsAlive'
However when using the interactive console I can do this:
if p.checkIsAlive() == True and e.checkIsAlive() == True:
... print('they are')
...
they are
all I want to do is call the boolean values for checkIsAlive to determine whether the two objects fight. It works in every other respect and I could just use:
if p.health <= 0 or e.health <= 0:
however that would make my checkIsAlive() method pretty useless when i would also want to be able to recycle as much code ass possible.
I really can't figure out why it is behaving this way and would sure love to understand it. Thanks in advance for your input.
As was pointed out swiftly in the comments above. I had missed a typo in the attribute name checkIsAlive.

can't get this python program to work [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
This is the vector2 module:
class Vector2(object):
"this calculates the vector between two points"
def __init__(self , x = 0.0, y = 0.0):
self.x = x
self.y = y
def __str__(self):
return "( %s,%s )"%(self.x, self.y)
#classmethod
def from_points(cls,p1,p2):
return cls(p2[0]-p1[0],p2[1]-p1[1])
#the magnetude of a vector is the distance between two points
def get_magnetude(self):
return math.sqrt(self.x**2+self.y**2)
def normalize(self):
magnetude = self.get_magnetude()
self.x /= magnetude
self.y /= magnetude
#rhs stands for right hand side
def __add__(self,rhs):
return Vector2(self.x + rhs.x,self.y+rhs.y)
def __sub__(self,rhs):
return Vector2(self.x-rhs.x,self.y-rhs.y)
def __neg__(self):
return Vector2(-self.x, -self.y)
def __mul__(self,scalar):
return Vector2(self.x*scalar,self.y*scalar)
def __div__(self,scalar):
return Vector2(self.x /scalar, self.y/scalar)
And this is the main program, which imports vector2:
background_image_file = 'download.jpeg'
sprite_image_file = 'images.jpeg'
import math
import pygame
from pygame.locals import*
from sys import exit
import vector2
pygame.init()
screen = pygame.display.set_mode((640,480), 0 ,32)
background = pygame.image.load(background_image_file).convert()
sprite = pygame.image.load(sprite_image_file).convert_alpha()
clock = pygame.time.Clock()
position = Vector2(100.0, 100.0)#the starting point coordonates
heading = Vector2()#a vector without its magnetude(unit vector)
speed = 250.0
running = True
while running:
for event in pygame.event.get():
if event.type == QUIT:
exit()
if event.type == MOUSEBUTTONDOWN:
destination_x = event.pos[0]-sprite.get_width()/2
destination_y =event.pos[1]-sprite.get_height()/2
destination = (destination_x, destination_y)
heading = Vector2.get_magnetude(position,destination)#
heading.normalize()#a vector without magnetude,just direction
screen.blit(background, (0,0))
screen.blit(sprite, position)
time_passed = clock.tick()
time_passed_seconds = time_passed / 1000.0
distance_moved = time_passed_seconds * speed
position += (heading * distance_moved)
pygame.display.update()
I am learning Python and pygame by my self with (Beginning Game Development with Python and Pygame - From Novice to Professional (2007)) and I can't get the program to work. Also can someone please explain to me why the author use position = Vector2(100.0,100.0) and position = Vector2() to create new vectors?
It keeps saying :
traceback (most recent call last):
File "/home/moussa/Documents/python /vector_movement.py", line 21, in <module>
position = Vector2(100.0, 100.0)#the starting point coordonates
NameError: name 'Vector2' is not defined
I'm guessing that the code in the question is actually split between two files, one with the Vector2 class (in vector2.py) and the rest in some other file (which imports vector2).
The issue you're running into is that you're not accessing the class correctly. In your main module, you need to use vector2.Vector2 to access the class within its module.
Or, if you'd prefer to have easier access to the class, you could instead change your import from import vector2 to from vector2 import Vector2. This puts the class into the main module's namespace, so you can access it directly as Vector2.
As for the use of position = Vector2(100.0,100.0), this is a call to the Vector2 class's constructor. It creates an instance of the class, initializes it with the values 100 for x and 100 for y, and then binds it to the variable position. You can then use the various methods and operators that the class defines to update the instance, or get new values. For instance, the later line position += (heading * distance_moved) first multiplies the vector heading by the scalar distance_moved, then adds the vector result to position. You could do this with values in lists or tuples, but it would be much more complicated (you'd need to add and multiply the components of the vectors yourself).

Categories

Resources