class Player:
def __init__(self, name=None):
self.name = name
self.score = 0
def add_score(self, score):
self.score = self.score + score
class HumanPlayer(Player):
def __init__(self):
Player.__init__(self, name="Human")
class ComputerPlayer(Player):
def __init__(self):
Player.__init__(self, name="Eliza")
class Score:
def __init__(self, human, computer):
self.human = human
self.computer = computer
def add_score(self, player, score):
self.player.add_score(score)
我的问题是Score
类中的add_score
方法。你知道吗
在Python上下文中:
既然human
和computer
都是从Player
类继承的(它们有自己的方法,但在这个问题中被省略了),那么我如何在add_score
方法中引用它们呢?(要清楚:我想对从Player
类继承的任何对象说add_score
。[如果对来自Player
类的任何对象或从Player
类继承的任何对象表示“add_score
”,这有关系吗?])你知道吗
好吧,您在示例中使用的是python,所以这个问题有一些答案。这是一种面向对象的方法,然后是pythonic方法。你知道吗
OOP的方法是,您的
__str__
(python版本的ToString
)将是抽象的(或者以其他方式实现),您可以在派生类中重写它。不过,老实说,您不会使用ToString
,而是专门为此定义一个抽象方法。也许PrintScore
。你知道吗也就是说,在这个例子中,OOP的用法也不是很好。
ComputerPlayer
和HumanPlayer
是否有不同的实现,从而需要派生类?给你的例子(也许你有更多的计划),你没有,你可以使用一个Player
类并创建一个属性“IsAI
”。对电脑播放器设置为true,对人类播放器设置为false。你知道吗我不想让这听起来很关键,所以请不要这么想。我只是想提供一些指导。
相关问题 更多 >
编程相关推荐