我正在编写纸牌游戏。如何通过父类将已经创建的卡片分配给对象?
我试图用这样的方法创建一个新对象:
name = Card(suit1, face1, value1)
但是由于我在此之前声明了名称,因此它无法正常工作。
如果在定义变量name
之后打印名称,则输出为:7Hearts, 7Diamonds, 7Clubs, 7Spades, 8Hearts, 8Diamonds...
我想在Card类中创建对象,以便为
print(7Hearts.suit, 7Hearts.face, 7Hearts.value)
是
>>> (Hearts, 7, 7)
或
print(AceSpades.suit, AceSpades.face, AceSpades.value)
>>> (Spades, Ace, 11)
from random import *
class Card(object):
def __init__(self, suit, face, value):
self.suit = suit
self.face = face
self.value = value
class Deck(Card):
def __init__(self):
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades']
ranks = range(7, 15)
for rank1 in ranks:
for suit1 in suits:
if rank1 == 11:
face1 = 'Jack'
value1 = 2
elif rank1 == 12:
face1 = 'Queen'
value1 = 3
elif rank1 == 13:
face1 = 'King'
value1 = 4
elif rank1 == 14:
face1 = 'Ace'
value1 = 11
else:
face1 = str(rank1)
value1 = rank1
name = "{0}{1}".format(face1, suit1)
答案 0 :(得分:2)
您既不需要也不想继承。 Deck
只是卡的集合。
class Deck(object):
def __init__(self):
self.cards = []
suits = ['Hearts', 'Diamonds', 'Clubs', 'Spades'],
ranks = {11: 'Jack', 12: 'Queen', 13: 'King', 14: 'Ace'}
values = {11: 2, 12: 3, 13: 4, 14: 11}
for suit in suits:
for rank in range(7,15):
card_rank = ranks.get(rank, str(rank))
value = values.get(value, value)
self.cards.append(Card(suit, card_rank, value))
您可能会使用继承来代表不同种类的套牌:扑克套牌,pinochle套牌等。Deck
本身具有用于改组的方法,但是每个子类都会构造{ {1}}个适合该卡组的对象。