Giacomo Saracchi
Giacomo Saracchi

Reputation: 25

Problem with nested Python Class definition: defined two classes using same syntax but one raises "undefined name" errors

I have defined two Classes containing nested classes in apparently (to me) the same way using textbook syntax. However one of them raises undefined name errors and I do not understand why.

class Game:
    class Hand:
        def __init__(self, players, dealer, count):
            self.players = players
            self.dealer = dealer
            self.count = count
    
    def __init__(self, rules):
        self.rules = rules
        self.hand = self.Hand(players, dealer, count)
        
class Player:
    class SubPlayer:
        def __init__(self, name, cards, cards_sum, hand):
            self.name = name
            self.cards = cards
            self.cards_sum = cards_sum
            self.hand = hand 
                
    def __init__(self, name, stack, bet, cards, cards_sum, hand, subPlayers, is_insured):
        self.name = name
        self.stack = stack
        self.bet = bet
        self.cards = cards
        self.cards_sum = cards_sum
        self.hand = hand
        self.subPlayers = subPlayers
        self.is_insured = is_insured
        self.subPlayer = self.SubPlayer(name, cards, cards_sum, hand)

The errors are raised in the Game class's init function, where I try to connect it to the Hand nested class, specifically the line "self.hand = self.Hand(players, dealer, count)". The errors read undefined names player, dealer, count. The Player class runs just fine and I have used it already in my program. Why is this happening? How do I fix it?

Thanks

Upvotes: 1

Views: 27

Answers (1)

Adam.Er8
Adam.Er8

Reputation: 13393

Game's __init__ function doesn't have params for players, dealer, count.

modify it's definition to:

    def __init__(self, rules, players, dealer, count):
        self.rules = rules
        self.hand = self.Hand(players, dealer, count)

(just like Player's __init__ also has all the params SubPlayer has..)

Upvotes: 2

Related Questions