美好的一天..
我在类里面的学习过程有点困难。让我展示我的代码,以及发生了什么。
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"
因此,在这段代码中,我尝试使用奇怪的投注系统来模拟轮盘游戏。它的工作原理类似于 Martingale,但我不是加倍,而是遵循斐波那契数列。
所以我的问题是我收到了这个错误:
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
我的问题。为什么?我的意思是,我正在调用同一个类中的函数?为什么我收到全局错误?
最佳答案
在方法中,您可以将 self
作为对实例的引用。您可以通过该引用访问该实例上的方法:
self.gamble()
这里没有全局的gamble
函数;该方法是 Simulation
类的一部分。这适用于所有方法;您必须对 self
调用 closeFile
、lose
、win
和 write
例如,也是如此。
关于Python:类:调用同一个类中的函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22281929/