Python: Class: Calling a function in the same class - python

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
>>>

Related

Why doesn't Python see a specified int() attribute?

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.

Getting a value from a class using a return statement within the class

class Player1:
base_HP = 300
def getBHP(self):
return self.base_HP
jogador1 = Player1
jogador1_hp = jogador1.getBHP() #Functions and Class calls must end with brackets.
print(jogador1_hp)
That's the code I'm using to get the player HP and i want to save it at jogador1_hp.
How ever this is what iam getting:
C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
<function Player1.getBHP at 0x02C131E0>
Process finished with exit code 0
Even if i do as below, I'm still getting a blank console.
class Player1:
base_HP = 300
def getBHP(self):
print(self.base_HP)
jogador1 = Player1
jogador1.getBHP
EDIT: I fix it ,i just needed to add "()" when i create the object!
jogador1 = Player1()
jogador1_hp = jogador1.getBHP()
You have to call methods for them to execute.
jogador1_hp = jogador1.getBHP()
You don't instantiate the Player1 class. In your code, jogador1 is just another name for the Player1 class. You should call the class to instantiate it, like: jogador1 = Player1()
If i use jogador1_hp = jogador1.getBHP() i get this :
C:\Users\joaol\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/joaol/PycharmProjects/FirstProgram/Main.py
Traceback (most recent call last):
File "C:/Users/joaol/PycharmProjects/FirstProgram/Main.py", line 19, in <module>
jogador1_hp = jogador1.getBHP()
TypeError: getBHP() missing 1 required positional argument: 'self'
Process finished with exit code 1

Create a class within a class and instance in outer scope?

I am trying to implement consumer - producer problem in Python… The one question I have is whether I can create a class within a class and create an object of it in the outer scope as in the code below:
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
app=Main()
I am getting the following error:
Traceback (most recent call last): File "/Users/sohil/Desktop/sync.py", line 55, in <module>
app=Main() File "/Users/sohil/Desktop/sync.py", line 36, in __init__
self.producer=Producer(processNumber,random.random()) NameError: global name 'Producer' is not defined
Change the order.
class Producer(threading.Thread):
def __int__(self,ProducerID,serviceTime):
self.id=ProcucerID
self.serviceTime=serviceTime
def run(self):
#mutexProducer.acquire()
#Entering Critical section
print queue.qsize()
if queue.full():
sleep(random.random())
else:
print "Customer %d Enters the Queue" %(self.id)
class Main(threading.Thread):
def __init__(self):
processNumber = 0
queue_size=5
self.mutexProducer=thread.allocate_lock()#mutex variablaes
self.mutexConsumer=thread.allocate_lock()
self.mutexTeller=thread.allocate_lock()
self.queue=Queue.Queue(maxsize=queue_size)
self.producer=Producer(processNumber,random.random())
Python is an interpreted language which executes from top to bottom so any dependencies must be declared at the top.

Class Attribute is clearly there, but python cant find it

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.

How can I call a class with type (type)

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.

Categories