从另一个函数调用变量

时间:2016-03-16 09:57:27

标签: function python-3.x variables return return-type

下面的函数给出了这个错误:

" 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 ? 如果我执行返回,它将退出主要功能,我不想这样做...有什么想法吗?

1 个答案:

答案 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 ....
    
相关问题