1 回答

TA贡献1877条经验 获得超1个赞
Player 类和 Computer 类都固有的 Deck 类
这不是理想的方法。如果两个类在概念上满足“是一个”关系,则该类应仅从另一个类继承。例如,Dog 应该从 Animal 继承,因为狗是一种动物。牌手不应继承牌组,因为牌手不是牌组。
与其继承,不如尝试使牌组成为玩家和计算机对象的属性。如果甲板对象是可变的,则对它的更改将从两个对象都可见。
class Deck:
def __init__(self):
self.cards = ["Pot of Greed", "Black Lotus", "Ace of Spades", "Draw Four"]
class Player:
def __init__(self, name, deck):
self.name = name
self.deck = deck
class Computer:
def __init__(self, difficulty, deck):
self.difficulty = difficulty
self.deck = deck
d = Deck()
p = Player("Steve", d)
c = Computer("Easy", d)
#confirm that the player and computer decks are the same object
print(p.deck is c.deck)
#changes made to the deck via p will be observable from c and vice versa
p.deck.cards.append("How to Play Poker Instruction Card")
print(c.deck.cards)
添加回答
举报