简体   繁体   English

从另一个函数调用变量

[英]Calling variable from another function

The function below gives me this error: 下面的函数给我这个错误:

"UnboundLocalError: local variable 'housebank' referenced before assignment" “ UnboundLocalError:分配前引用了本地变量'housebank'”

def placeBet(table, playerDictionary, bet, wager):
    playerDictionary['You'][1].add(bet)
    housebank -= (wager*table[bet][0])
    table[bet][1]['You']=wager

The housebank variable is declared in my main function below: 在以下主函数中声明了housebank变量:

def main():
    housebank = 1000000
    table = {'7' : [9/1,{}]}
    playerDirectory = {'player1':[1,set(),True]}
    placeBet(table,playerDirectory, 10, 100)

How can I use housebank in the placeBet function? 如何在placeBet函数中使用房屋银行? If I do a return it will exit the main function, which I do not want to do... Any ideas? 如果返回 ,它将退出主要功能,我不希望这样做...有什么想法吗?

housebank is local to placeBet . housebank是本地placeBet There's three ways to do it that I can see: 我可以看到三种方法:

  • Make a class. 上课。

     class Foo: def __init__(): self.housebank = 1000000 def run(): # .... def placeBet(....): # .... self.housebank -= (wager*table[bet][0]) # .... def main(): Foo().run() 
  • Declare housebank in a wider scope: 在更大范围内声明housebank

     housebank = 1000000 def placeBet(....): # .... def main(): # .... 
  • Make placeBet a closure inside main : placeBet内关闭main

     def main(): housebank = 1000000 def placeBet(....): # .... # .... rest of main .... 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM