[英]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.我只是在 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.
所以你从2张牌开始。 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
:向对象添加字段的正确方法是使用
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).您可能会发现自己想要一个 Card 类,它知道如何从最高值到最低值排序卡片,或者能够按花色或数字收集卡片(EG 为 3 平分,或所有红心)。
您可以使用列表来实现所需的目标,而不是为您可能拥有的每个值分配一个属性
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.