简体   繁体   中英

How do I add more variables to class if I don't know how many I would add (python)

I'm just making a blackjack game on python. So I have a player class and I set player's variables as the cards the user gets. So you start with 2 cards. But as the user wants to get more cards I have to add new cards to the class. How would I do that? It seems redundant to make a bunch of unassigned variables and assign them as the user gets more cards.

class Player:
    def __init__(self, pcard1, pcard2):
        self.Pcard1 = pcard1
        self.Pcard2 = pcard2

    def player_starting_cards(self):
        print("Your cards are " + str(self.Pcard1) + " and " + str(self.Pcard2))

Your best bet would be to have a list of cards and append to it. Something like:

class Player:
    def __init__(self, *cards):
        self.cards = cards

    def player_starting_cards(self):
        print("Your cards are " + " and ".join(self.cards))

The proper way to add fields to an object, however is with setattr :

>>> class A():
...     pass
...
>>> a = A()
>>> a.__dict__ # Contain object attributes
{}
>>> setattr(a, "my_attr", 42)
>>> a.__dict__
{'my_attr': 42}

Hope that helps.

Use some sort of collection type like a list of dict. These are single things that can hold multiple things.

EG:

class Player:
    def __init__(self, cards):
        self.card_list = cards

    def player_starting_cards(self):
        print("Your cards are {}".format(', '.join(self.card_list)))

player = Player(['qh', '3c'])
player.player_starting_cards()

You may finding yourself wanting a Card class that knows how to order cards from highest value to lowest, or able to collect cards by suit or numerically (3 deuces, or all hearts, for EG).

您可以使用列表来实现所需的目标,而不是为您可能拥有的每个值分配一个属性

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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