Home>

An error occurs if _suits is not defined even though it is already defined
Why?

class Card:
    _suits = ['♠', '♥', '♦', '♣']
    _number = [i for i in range (1, 14)]
    card = []
    card = [[(_suits [i], _number [j]) for i in range (4)] for j in range (13)]
Code
  • Answer # 1

    The code as in the question won't work because there are limited places where you can access class variables.

    For example, the desired function can be realized by cutting it into another function as follows.

    def create_set ():
        suits = ['♠', '♥', '♦', '♣']
        number = [i for i in range (1, 14)]
        return [[(suits [i], number [j]) for i in range (4)] for j in range (13)]
    class Card:
        card = create_set ()

    Or move to the constructor side.

    class Card:
        _suits = ['♠', '♥', '♦', '♣']
        _number = [i for i in range (1, 14)]
        def __init __ (self):
            self.card = [[(self._suits [i], self._number [j]) for i in range (4)] for j in range (13)]

  • Answer # 2

    wrong Requested deletion per answer