我试图在另一个对象的方法中调用一个对象

I'm trying to invoke an object within a method in a different object

我正在开发一个简单的扑克游戏,只是为了改善我的 OOP 体验,我 运行 陷入了一个可能超出我知识范围的错误。

程序是这样的,我有一个叫做 Deck() 的 class 当然是牌组,一个叫做 player 的 class 和一个叫做 [=60= 的 class ].在播放器 class 中,我有几种方法,但为了尽可能简短,我只会说出必要的方法。我有以下方法(在播放器 class 中)bet()、call() fold()、all_in() 和 player_choice()。我命名的前四个方法都是由 player_choice method() 调用的。然而,问题出在 bet()、all_in() 和 call 方法中。以下方法看起来像这样

        def all_in(self):
    table.table_money += self.money
    self.money = 0
    print('{} went all in!').format(self.name)

def cal(self, last_bet):
    if last_bet > self.money:
        while True:
            res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
            if res.lower() == 'y':
                self.all_in()
                break
            elif res.lower() == 'n':
                self.fold()
                break
            else:
                print('Invalid input. Try again...')
    else:
        table.table_money += self.money - last_bet
        self.money -= last_bet
        print('{} called.').format(self.name)


def bet(self, last_bet):
    res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
    table.latest_bet += res
    table.table_money += res
    self.money -= res
    print('{} has bet {}$').format(self.name, str(res))

问题是,当我调用这些方法之一并且该方法正在减去玩家的钱并将其添加到 table.table_money()(如上面的代码所示)时我收到一个 NameError 说 'table' 未定义。

这里是 Table() class:

    class Table():
def __init__(self):
    self.table_money = 0
    self.latest_bet = 0

    if players == '':
        print('Table is empty!')
    else:
        print(str(len(players)) + ' players on the table.')

def list_table(self):
    for i in players:
        print(i.__str__())

我知道你可能在想我输入的是 table 而不是 Table。但他就是他,当我 运行 main() 函数中的代码时,我将一个 Table 对象初始化为一个名为 table 的变量,该变量应该与那个变量相同被 Player() class 方法调用。

这里是 main() 函数的简短视图:

    def main():
while welcome():
    rond = 1
    while rond <= 5:
        table = Table()
        deck = Deck()
        deck.deal()
        user = players[0]
        user.list_hand()
        user.player_choice(table.latest_bet)
        break
    break

问题的结构是这样的:

  1. 首先我定义播放器class。
  2. 2nd 我定义了 table。
  3. 3 我定义了 main()。

这是错误的输出:

    Traceback (most recent call last):
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 161, in <module>
    main()
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 157, in main
    user.player_choice(table.latest_bet)
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 38, in player_choice
    self.cal(last_bet)
    File "C:/Users/Alex/PycharmProjects/GUI_prject/venv/Lib/site- 
    packages/resors2.py", line 71, in cal
    table.table_money += self.money - last_bet
    NameError: name 'table' is not defined

如果我没有提供足够的程序详细信息,请告诉我,如果需要,我会分享更多。如果我没有以最好的方式解释所有这些并且 post 太长,我深表歉意。我更感激任何评论。 感谢阅读。

完整代码:

    import random as r

    suits = ['H','C','S','D']
    values = ['A','2','3','4','5','6','7','8','9','10','J','Q','K']
    players = []

    class Card():
        def __init__(self, suit, value):
            self.suit = suit
            self.value = value

        def valu(self):
            return self.value + self.suit

    class Player():
        def __init__(self, name, money):
            global players
            self.name = name
            self.money = money
            print(self.name+ ' joined the table!')
            players.append(self)
            self.hand = []

        def __str__(self):
            return '{}: {}'.format(self.name, str(self.money))

        def add_to_hand(self, cards):
            self.hand.append(cards)

        def list_hand(self):
            for i in self.hand:
                print(i)

        def player_choice(self, last_bet):
            while True:
                resu = input('c - Call | b - bet | a - all in | f - fold\n>>> 
    ').lower()
            if resu == 'c':
                self.cal(last_bet)
                break
            elif resu == 'b':
                self.bet(last_bet)
                break
            elif resu == 'a':
                self.all_in()
                break
            elif resu == 'f':
                self.fold()
                break
            else:
                print('Invalid input. Try again...')


        def all_in(self):
            table.table_money += self.money
            self.money = 0
            print('{} went all in!').format(self.name)

        def cal(self, last_bet):
            if last_bet > self.money:
                while True:
                    res = input('You dont have enough money to call.\tyou have=> {}\nDo you want to go all in?\ty/n\n>>> ').format(str(self.money))
                    if res.lower() == 'y':
                    self.all_in()
                    break
                    elif res.lower() == 'n':
                    self.fold()
                    break
            else:
                print('Invalid input. Try again...')
        else:
            table.table_money += self.money - last_bet
            self.money -= last_bet
            print('{} called.').format(self.name)


    def bet(self, last_bet):
        res = int(input('Enter bet below.\t must be over {}\n>>> '.format(str(last_bet))))
        table.latest_bet += res
        table.table_money += res
        self.money -= res
        print('{} has bet {}$').format(self.name, str(res))

    def fold(self):
        players.remove(self)
        print('{} has folded.').format(self.name)


    class Table():
        def __init__(self):
            self.table_money = 0
            self.latest_bet = 0

            if players == '':
                print('Table is empty!')
            else:
                print(str(len(players)) + ' players on the table.')

        def list_table(self):
            for i in players:
            print(i.__str__())




    class Deck():
        def __init__(self):
            self.cards = []

            for suit in suits:
                for value in values:
                   self.cards.append(Card(suit, value).valu())

            r.shuffle(self.cards)

        def show_deck(self):
            return self.cards

        def shuffle_d(self):
            r.shuffle(self.cards)

        def deal(self):
            for p in players:
                for c in range(0, 1):
                    p.add_to_hand((self.cards.pop(), self.cards.pop()))

    #The welcome function is not a method for any of the classes above 

    def welcome():
        global players
print('''
        Welcome to the poker table. 
        q - Quit
        s - Take a seat
''')
res = ''
while res != 'q' or 's':
    res = input('>>> ')
    if res == 'q':
        return False
    elif res == 's':
        name = input('Enter your name: ')
        money = int(input('Enter how much money you wish to have(max 500$): '))
        Player(name, money)
        return True
    else:
        print('Invalid input. q - Quit\ts - Take a seat')



    def main():
        while welcome():
        rond = 1
            while rond <= 5:
                table = Table()
                deck = Deck()
                deck.deal()
                user = players[0]
                user.list_hand()
                user.player_choice(table.latest_bet)
                break
            break

    main()

尽量忽略未命中

tablesmain()函数中的局部变量。您应该将其添加为 player class.

的属性
def go_to_table(self, table):
    self.table = table

那么所有方法都应该使用 self.table 而不是 table。主要是:

def main():
    while welcome():
        rond = 1
        while rond <= 5:
            table = Table()
            deck = Deck()
            deck.deal()
            user = players[0]
            user.go_to_table(table)
            user.list_hand()
            user.player_choice(table.latest_bet)
            break
        break

您将类型(如 Table)与该类型对象的单个实例混淆,如 table = Table() 之后的 table

table = Table()新建了一个Table类型的对象,赋值给变量table,方便以后引用。但是,此变量是在函数 main 内部定义的,并且仅在那里可用。在方法 cal 中(我认为这是 call 的拼写错误),没有 table,因为你可能有很多游戏正在进行并且它不知道什么 table 它属于。

由于玩家坐在特定的 table,因此在 Player 中保留对 Table 的引用并在其构造函数中为其分配一些内容是有意义的喜欢 self.table = table。然后您可以使用 self.table.

call 方法引用它
class Player:
    def __init__(self, table):
        self.table = table

    def call(self):
        self.table.money += 1


class Table:
    def __init__(self):
        self.money = 0


table = Table()
player = Player(table)
player.call()
print(table.money)