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.
Related
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.
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 2 years ago.
Improve this question
I am actually learning python3 and not able to figure it why it is so
class Load():
def __init__(self):
print("Starting Now")
self.player = []
def player_Stats(self,filename):
with open(filename) as my_names:
names = my_names.readlines()
for one in names:
one.replace("\n","")
self.player.append(one.split[":"][0])
print(player)
print(Load.player_Stats("players.txt"))
It is giving me an error
Traceback (most recent call last):
File "test.py", line 56, in <module>
print(Load.player_Stats("players.txt"))
TypeError: player_Stats() missing 1 required positional argument: 'filename'
and I am not getting it why.
You have to define an object or make the function static.
Option 1: Define Object:
class Load():
def __init__(self):
print("Starting Now")
self.player = []
def player_Stats(self,filename):
with open(filename) as my_names:
names = my_names.readlines()
for one in names:
one.replace("\n","")
self.player.append(one.split[":"][0])
print(player)
load = Load()
print(load.player_Stats("players.txt"))
Option 2: Static method:
class Load():
def __init__(self):
print("Starting Now")
self.player = []
#staticmethod
def player_Stats(filename):
with open(filename) as my_names:
names = my_names.readlines()
for one in names:
one.replace("\n","")
self.player.append(one.split[":"][0])
print(player)
print(Load.player_Stats("players.txt"))
Try this instead:
lass Load():
def __init__(self):
print("Starting Now")
self.player = []
def player_Stats(self,filename):
with open(filename) as my_names:
names = my_names.readlines()
for one in names:
one.replace("\n","")
self.player.append(one.split[":"][0])
print(player)
load = Load()
print(load.player_Stats("players.txt"))
The problem was that when you have a class, you must create an instance of it. Then you can call it's methods.
You need to create a new instance of Load in order to use the player_Stats method:
load = Load()
print(load.player_Stats("players.txt"))
Also, there are some other errors in your code:
self.player.append(one.split[":"][0])
# should be
self.player.append(one.split(":")[0])
print(player)
# should be
print(self.player)
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
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
For some reason, the class variable self cannot be defined in a function.
Function:
def pickapoo_specialattack(opponent):
print("PICKAPOO's FLATULENCE BOLTS WAS EFFECTIVE")
self.damage -= float(self.damage / 20)
damage_dealt = random.randrange(200, 250)
defender.health -= damage_dealt
print("\nPICKAPOO's DAMAGE RATING WAS DECREASED BY 20%")
print("PICKAPOO's DAMAGE RATING IS NOW {}".format(str(self.damage)))
return self.damage
Class:
class Deskemon(object):
def __init__(self, name, health, damage, defense):
self.base_name = name
self.base_health = health
self.base_damage = damage
self.base_defense = defense
self.name = self.base_name
self.health = self.base_health
self.damage = self.base_damage
self.defense = self.base_defense
Traceback:
Traceback (most recent call last):
File "DESKEMON PRE ALPHA.py", line 378, in <module>
Battle(deskemon, Jack)
File "DESKEMON PRE ALPHA.py", line 168, in Battle
Deskemon_Attack(D1, D2, special=(random.randrange(1, 100) <= 45))
File "DESKEMON PRE ALPHA.py", line 216, in Deskemon_Attack
pickapoo_specialattack(defender)
File "DESKEMON PRE ALPHA.py", line 115, in pickapoo_specialattack
self.damage -= float(self.damage / 20)
NameError: name 'self' is not defined
Here is my full code: http://pastebin.com/8Xn6UCKS
that's because the self variable has to be explicitely given to methods in python. As you write it, are you expecting python to read your mind so it guesses that self shall be something from a class your function is not related at all with?
So to have it bound you need:
add self to argument list of def pickapoo_specialattack(self, opponent)
to move pickapoo_specialattack(opponent) in your Deskemon class
looking further in your code, what you're doing is definitely wrong, as you're defeating the whole purpose of OOP! Use classes and subclasses to do what you're aiming.
Let me give you an incomplete example of what I mean:
class Deskemon(object):
def specialattack(self, opponent):
raise NotImplementedError
…
class Pickapoo(Deskemon):
def specialattack(self, opponent):
… # content of the pickapoo_specialattak() function
class Tamosha(Deskemon):
def specialattack(opponent):
… # content of the tamosha_specialattak() function
and then:
def main():
pickapoo = Pickapoo(…)
tamosha = Tamosha(…)
instead of monkey patching Deskemon instances, use proper OOP conception and make Deskemon the base class of all your instances. Then you create a specialized instance for each Deskemon object, and that's the thing you initialize.
N.B.1: you should init all your objects in a main function:
N.B.2: you should place all your code at the end in a main function:
def main():
# init
pickapoo = Pickapoo(…)
tamosha = Tamosha(…)
lilwilly = Lilwilly(…)
bigbboy = Biggboy(…)
# start up
print("Welcome to Deskemon Pre-Alpha V1.2".upper())
…
# play loop
while True:
deskemon_selection_menu()
deskemon_selection_input = input("> ")
if deskemon_selection_input == "1":
deskemon = tamosha
elif deskemon_selection_input == "2":
deskemon = pickapoo
elif deskemon_selection_input == "3":
deskemon = lilwilly
elif deskemon_selection_input == "4":
deskemon = biggboi
else:
continue
print("You have selected {} as your Deskemon".upper().format(deskemon))
break
# shut down
print("Professor Andrew: Alright Jack, it's time to pick your Deskemon.")
…
print("Jack: OI! " + name + "!")
time.sleep(1)
Battle(deskemon, Jack)
if __name__ == "__main__":
main()
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I'm in a python class with a dumb teacher and I havent been able to get anything to work right. Here's a simple program i'm just trying to get to work once i know it doesn't really gget the average.
>>> class two:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Number? 5
Traceback (most recent call last):
File "<pyshell#28>", line 1, in <module>
class two:
File "<pyshell#28>", line 9, in two
main()
File "<pyshell#28>", line 7, in main
y= average(x+1,x)
NameError: global name 'average' is not defined
Your error happens because you do not have any global name average in scope when you use it.
You seem to be confused about when and whether to use the class keyword. In your particular example, you don't need it -- both average and main want to be global functions, not class methods.
Try this program instead:
def average(a,b):
return int((a+b)/2)
def main():
num = input("Number? ")
x= int(num)
y= average(x+1,x)
print(y)
main()
Alternatively, if you want to learn about classes:
class two:
def __init__(self, x,y):
self.x = x
self.y = y
def average(self):
return (self.x + self.y)/2
def main():
t = two(7,42)
print(t.average())
main ()
Notice how the declaration of average now includes a self parameter -- this links the call to a particular two object. Notice also how the invocation of average changed: it is now t.average(). In this case, t is the specific object which will be passed as the first parameter of two.average().
def average(a,b):
return int((a+b)/2)
def main():
print 'enter a number'
num = raw_input()
y = average(int(num)+1,int(num))
print y
main()