http://i.imgur.com/9Xin1x0.png
以下是Black Jack测试案例中的课程及其关系。
在python IDLE中我导入“BlackJackGame
”并将“game
”变量绑定到“BlackJackGame()
”,因此我初始化了一个黑杰克游戏。
现在如果我想初始化很多Black Jack游戏,我希望“Card”类在每个游戏中都有不同的属性呢?
例如,在一个黑杰克游戏中,卡片将具有经典套装,例如['Diamond', 'Club', 'Heart', 'Spade']
,而在其他情况下,它们会制作套装,例如['Test1', 'Test2', 'Test3', 'Test4']
。
简而言之,当我将BlackJackGame()
绑定到变量时,如何修改“Card”类属性,以便Black Jack的不同游戏有不同类型的卡?
编辑:我编写了一个测试用例,以便在实践中显示此问题
class Card(object):
def __init__(self, attribute = 'Test 1'):
self.attribute = attribute
class Player(object):
def __init__(self):
self.card = Card()
class Deck(object):
def __init__(self, card = Card()):
self.card = card
class MainDeck(object):
def __init__(self, deck = Deck()):
self.deck = deck
class BlackJackGame(object):
def __init__(self, maindeck = MainDeck(), player = Player()):
self.maindeck = maindeck
self.player = player
#Initializing first game
game1 = BlackJackGame()
#We access "Card" classes that reside in "Deck" and "Player",
#to test "Card" class's variable.
print(game1.maindeck.deck.card.attribute) #Prints 'Test 1'
print(game1.player.card.attribute) #Prints 'Test 1'
#Initializing second game, but this time so that "Card" class's
#attribute has a different value, when card is in "Deck"
game2 = BlackJackGame(maindeck = MainDeck(deck = Deck(card = Card(attribute = 'Test 2'))))
#We test if the attribute assignment works correctly
print(game2.maindeck.deck.card.attribute) #Prints 'State 2'
现在你看,在第二个黑杰克游戏中,我希望Card
具有与第一个不同的属性值,但是我这样做的方法非常痛苦,而且它只会改变Cards
中的Deck
,我希望Card
在不同的黑杰克游戏中拥有不同类型的属性值。
答案 0 :(得分:1)
Card = namedtuple('Card', 'attribute value')
class Deck(object):
def __init__(suits, basic_card):
'''Take list of suits'''
self.cards = [basic_card._replace(suit=suit, value=value)
for value in range(1, 14)
for suit in suits]
用法:
poker = BlackJackGame(Deck(suits=['Hearts', 'Spades', 'Clubs', 'Diamonds'],
basic_card=Card(attribute='Test 1', value=0))
uno = BlackJackGame(Deck(suits=['Red', 'Yellow', 'Green', 'Blue'],
basic_card=Card(attribute='Test 2', value=0)))