下面的函数给出了这个错误:
" UnboundLocalError:本地变量' housebank'在分配之前引用"
def placeBet(table, playerDictionary, bet, wager):
playerDictionary['You'][1].add(bet)
housebank -= (wager*table[bet][0])
table[bet][1]['You']=wager
housebank变量在我的主函数中声明:
def main():
housebank = 1000000
table = {'7' : [9/1,{}]}
playerDirectory = {'player1':[1,set(),True]}
placeBet(table,playerDirectory, 10, 100)
如何在placeBet函数中使用 housebank ? 如果我执行返回,它将退出主要功能,我不想这样做...有什么想法吗?
答案 0 :(得分:1)
housebank
位于placeBet
的本地。我可以看到有三种方法可以做到:
上课。
class Foo:
def __init__():
self.housebank = 1000000
def run():
# ....
def placeBet(....):
# ....
self.housebank -= (wager*table[bet][0])
# ....
def main():
Foo().run()
在更广泛的范围内声明housebank
:
housebank = 1000000
def placeBet(....):
# ....
def main():
# ....
在placeBet
:
main
一个闭包
def main():
housebank = 1000000
def placeBet(....):
# ....
# .... rest of main ....