Why am i getting this attribute error?
class GameState(object):
"""Keeps track game state variables"""
def __init__(self, convo_flag=0, characters_talked_to=0, convo_log=(None)):
self.convo_flag = convo_flag
self.characters_talked_to = characters_talked_to
self.convo_log = convo_log
def welcome_screen():
global LAST_NAME
global BULLY
global DAY
raw_input(messages.WELCOME)
LAST_NAME = raw_input(messages.LAST_NAME)
BULLY = characters.random_character(cclass='Camper', gender='m')
print 'Your name is Pickett %s' % LAST_NAME
messages.print_messages([
messages.EXPLANATION,
messages.BUS_LOADING,
messages.CRACK,
messages.GAME_KID_LOST])
return week_one(DAY)
def week_one(day):
if day == 1:
messages.print_messages(messages.WEEK_ONE[day])
campers = characters.random_character_sample(cclass='Camper', count=5)
people_outside_theater = campers + [characters.TROID]
while GameState.characters_talked_to != 3:
I dont get why im getting this attribute error, i totally declared it in that constructor, is there something i am missing were i need to declare it outside the constructor? This is really racking my brain.
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "pickett.py", line 44, in welcome_screen
return week_one(DAY)
File "pickett.py", line 52, in week_one
while GameState.characters_talked_to != 3:
AttributeError: type object 'GameState' has no attribute 'characters_talked_to'
You need to create an instance in order you use your class like this:
gameState = GameState()
while gameState.characters_talked_to != 3:
In your code you were trying to access class-level attribute which is not defined in your class.
Your __init__ function sets characters_talked_to on self, which is an instance of GameState.
You did not set it on GameState, which is a class.
Neither did you create any instances of GameState, so in any case __init__ is never called by your program.
Related
Normally, to debug a function outside a class I will assign all of its parameters then run & check the function code line by line. (Yes, I know this might not be a professional way!). However, for a function inside a class, it gets error because of the self
For eg, whichever line I run inside this class, it will say:
self.issue_date = issue_date
Traceback (most recent call last):
File "<ipython-input-70-6d3e45750988>", line 1, in <module>
self.issue_date = issue_date
NameError: name 'self' is not defined
So, how to run code inside a class line by line? Or how do you guys debug a function inside a class?
Below is an eg of my class.
class fixed_bond:
def __init__(self, issue_date, settlement_date, first_coupon_date, maturity_date, face_value, df1, df2, coupon_rate, roll, coupon_frequency, day_count_convention):
##################################################################################
#Setting up inital attributes
##################################################################################
self.issue_date = issue_date
self.settlement_date = settlement_date
self.first_coupon_date = first_coupon_date
self.maturity_date = maturity_date
self.face_value = face_value
self.coupon_rate = coupon_rate
if self.roll =='Following':
for i in range(self.number_of_periods):
while cash_flow_dates[i].weekday() < 5:
cash_flow_dates[i]=cash_flow_dates[i] + relativedelta(days = 1)
.......
(end of class eg)
We are trying to run a pygame program but get an AttributeError. This is the error message we get and the error they say is on line 78 in the Food Spawner Class.
Traceback (most recent call last):
File "\\lchs-file01\staff$\Tyson.Friesen\SYSTEM\Desktop\Python Junk File.py", line 120, in <module>
food_position = food_spawner.spawn_food()
File "\\lchs-file01\staff$\Tyson.Friesen\SYSTEM\Desktop\Python Junk File.py", line 78, in spawn_food
if self.isFoodOnScreen == False:
AttributeError: 'FoodSpawner' object has no attribute 'isFoodOnScreen'
This is the code we are trying to run and we are slightly new to pygame so detailed help would be great. Thanks.
class FoodSpawner():
#----------------------sets the food to spawn randomly
def __init__(self):
self.position = [random.randrange(1,50)*10], [random.randrange(1,50)*10]
self.is_food_on_screen = True
#----------------------
#----------------------resets food if it spawns of screen
def spawn_food(self):
if self.isFoodOnScreen == False:
self.position = [random.randrange(1,50)*10], [random.randrange(1,50)*10]
self.is_food_on_screen = True
return self.position
#----------------------
def set_food_on_screen(self,b):
self.isFoodOnSceen = b
From what I can tell, you're setting the attribute self.is_food_on_screen = True in __init__ and trying to access self.isFoodOnScreen which is only set in set_food_on_screen
If you call spawn_food before set_food_on_screen then you will hit this exception because self.isFoodOnScreen won't exist as an instance attribute yet.
Seems like you want to be using self.is_food_on_screen wherever you are using self.isFoodOnScreen
You created self.is_food_on_screen = True in your __init__ method,
...
and then tried to set isFoodOnScreen (in camel-case, instead of with underscores)...
I suspect your error will go away if you make the names the same.
I am building a Python-based, single-player, word-based, MMORPG game. I am a beginner and wish this to be a simple task. I have coded the moving part, in which the character moves from one site to another. It seems to not work, as Python seems to not be able to see my attributes. This is the error message:
Traceback (most recent call last):
File "C:/Users/lenovo/Desktop/Maelstrom/Maelstrom Move.py", line 51, in
place = test.place
AttributeError: 'Player' object has no attribute 'place'
This is my code:
class Player(object):
"""The player."""
def __init__(self,name="name",inv=[],equip=[],stats=[],place=int("001"),knownplaces={}):
self.name = input("What name do you want?")
knownplaces[int("001")]="Ruby City"
knownplaces[int("002")]="Ruby Inn"
knownplaces[int("003")]="Ruby Forests"
knownplaces[int("004")]="Ruby Countryside"
knownplaces[int("005")]="Witch Hideout"
def __str__():
rep = self.movepossible
def movepossible(self,position):
#001--Ruby City
#002--Ruby Inn
#003--Ruby Forests
#004--Ruby Countryside
#005--Witch Hideout
if position==int("001"):
possible=[int("002"),int("003")]
return possible
elif position==int("002"):
possible=[int("001")]
return possible
elif position==int("003"):
possible=[int("001"),int("004")]
return possible
elif position==int("004"):
possible=[int("001"),int("003"),int("005")]
return possible
elif position==int("005"):
possible=[int("004")]
return possible
else:
return null
def move(self,position):
possiblewords=[]
print('Choose between paths:'/n)
possible = movepossible(self, position)
for m in range(0,len(possible),1):
possiblewords.append(knownplaces[possible[m]])
for n in range(0,len(possiblewords),1):
print(m+':'+possiblewords[m-1] /n)
choice=input('Make your choice...')
if choice-1 <= len(possiblewords):
self.place=possible[choice-1]
def showposition(self):
print(knownplaces[self.place])
test = Player()
while True:
place = test.place
test.move(place)
test.showposition()
At the time the line place = test.place is executed, the place attribute on your Player instance has not been defined.
The first time the place attribute gets set is in the move() method. i.e. Attempting to access place before calling move() will result in the error you are observing.
You should assign a default value to self.place in the initializer for the Player class.
Good day..
I'm kinda struggling in my learning process in Class. Let me show my code, and what is happening.
from random import randint
print "Start"
class Simulation (object):
def __init__(self):
self.bankroll= 5000
self.bet=0
self.betLevel= 0
self.betList=[5,5,5,10,15,25,40,65,100]
self.wlist=[]
self.my_file=open("output.txt","w")
self.winningNumber=0
self.myNumber=[4,5,7,8]
self.testCase=1
self.my_file.write("Test case Bet Number Outcome Bankroll")
def gamble(self):
self.bet=self.betList[self.betLevel]
if self.bankroll < 1000 :
self.bet= 5
self.winningNumber= randint(0,36)
if self.winningNumber in self.myNumber:
win()
else:
lose()
def win(self):
self.bankroll +=(17*self.bet)
self.wlist= [self.testCase,self.bet,self.winningNumber,"WIN",self.bankroll]
self.betLevel=0
write()
def lose(self):
self.bankroll -=self.bet
self.wlist= [self.testCase,self.bet,self.winningNumber,"LOSE",self.bankroll]
self.betLevel +=1
write()
def write(self):
self.my_file.write(" ".join(self.wlist))
def startSimulation(self):
for i in range (100):
gamble()
closeFile()
def closeFile(self):
self.my_file.close()
mySimulation= Simulation()
mySimulation.startSimulation()
print "DONE"
So in this code, I'm trying to simulating a roulette game, using a weird betting system. It works like Martingale, but instead of doubling, I follows Fibonacci sequence.
So my problem is that I got this error:
Traceback (most recent call last):
File "D:\Roulette simulation\python 3.py", line 44, in <module>
mySimulation.startSimulation()
File "D:\Roulette simulation\python 3.py", line 38, in startSimulation
gamble()
NameError: global name 'gamble' is not defined
My question. Why? I mean, I'm calling a function in the same class? Why I got the global error?
Within a method, you have self as a reference to your instance. You can access methods on that instance through that reference:
self.gamble()
There is no global gamble function here; the method is part of the Simulation class. This applies to all methods; you'll have to call closeFile, lose, win and write on self as well, for example.
Try running
self.gamble()
in class functions,self means class itself(someone use 'cls' instead of 'self'), so self.gamble means gamble function of this class
if you want to run a function in the position of class attribution
>>> class P:
name = 'name'
def getage(self):
return 18
age = property(getage)
>>> p = P()
>>> p.age
18
>>>
I'm making a game, and in the code two classes. One that defines the question, and the other that defines the 4 multiple choice answers. This is what I have:
class new_question(type):
""" The Question that displays on screen """
def __init__(self, question):
super(new_question, self).__init__(question = question)
def ask_quest(self):
global QUESTION
QUESTION = ask_question
QUESTION.value = question
That is my first class, and my second class is:
class answer(type):
""" Four answers that display in their own boxes """
def __init__(self, answers):
super(answer, self).__init__(answers = answers)
def all_answers(self):
global ANS1
global ANS2
global ANS3
global ANS4
ANS1 = poss_ans_1
ANS1.value = answers[0]
ANS2 = poss_ans_2
ANS2.value = answers[1]
ANS3 = poss_ans_3
ANS3.value = answers[2]
ANS4 = poss_ans_4
ANS4.value = answers[3]
All the variables are defined elsewhere in this file, and in others, but that's not the problem I'm having. When I go to call these classes I assume the best thing to do would be to call the individual function from the class in my main loop here:
def main():
load_image()
ans = answer(type)
ans.all_answers()
main()
However, when I run the program, I get this error:
Traceback (most recent call last):
File "C:\Users\Roger\Documents\Trivia New\main.py", line 83, in <module>
main()
File "C:\Users\Roger\Documents\Trivia New\main.py", line 82, in main
ans.all_answers()
AttributeError: type object 'type' has no attribute 'all_answers'
I'm not sure what's going on, but I've been at this same problem for 3 hours now, and still can't figure it out. If someone could help me, I would appreciate it.
Your classes should subclass object, not type.
Subclassing type makes your class a metaclass - the class of a class.