Python中关于继承的面向对象设计
我的问题是Python中关于继承的面向对象设计,python,oop,Python,Oop,我的问题是score类中的add\u score方法 在Python上下文中: 既然human和computer都是从Player类继承而来的(它们有自己的方法,但在这个问题中省略了),我如何在add\u score方法中引用它们?(需要明确的是:我想说,add_score到从Player类继承的任何对象上。[如果是说“add_score到从Player类继承的任何对象上,或者到从Player类继承的任何对象上”?]),您在示例中使用的是python,因此有几个问题的答案。有OOP的方法,还有P
score
类中的add\u score
方法
在Python上下文中:
既然
human
和computer
都是从Player
类继承而来的(它们有自己的方法,但在这个问题中省略了),我如何在add\u score
方法中引用它们?(需要明确的是:我想说,add_score
到从Player
类继承的任何对象上。[如果是说“add_score
到从Player
类继承的任何对象上,或者到从Player
类继承的任何对象上”?]),您在示例中使用的是python,因此有几个问题的答案。有OOP的方法,还有Python的方法
OOP实现这一点的方法是,您的\uu str\uuu
(python版本的ToString
)将是抽象的(或以其他方式通用实现),您将在派生类中重写它。不过,老实说,您不会使用ToString
——您应该专门为此定义一个抽象方法。也许PrintScore
也就是说,您在本例中对OOP的使用也不是很好。ComputerPlayer
和HumanPlayer
是否有不同的实现,从而需要派生类?考虑到你的例子(也许你有更多的计划),你没有。您可以使用一个Player
类并创建一个属性“IsAI
”。对于计算机玩家,将其设置为true,对于人类玩家,将其设置为false
我并不是说这听起来很关键,所以请不要这么认为。我只是想提供一些指导。好吧,您的示例中使用的是python,所以这个问题有一些答案。有OOP的方法,还有Python的方法 OOP实现这一点的方法是,您的
\uu str\uuu
(python版本的ToString
)将是抽象的(或以其他方式通用实现),您将在派生类中重写它。不过,老实说,您不会使用ToString
——您应该专门为此定义一个抽象方法。也许PrintScore
也就是说,您在本例中对OOP的使用也不是很好。ComputerPlayer
和HumanPlayer
是否有不同的实现,从而需要派生类?考虑到你的例子(也许你有更多的计划),你没有。您可以使用一个Player
类并创建一个属性“IsAI
”。对于计算机玩家,将其设置为true,对于人类玩家,将其设置为false
我并不是说这听起来很关键,所以请不要这么认为。我只是想提供一些指导。是否要添加表示所用语言的标记?对于1,你是说在你的
score
类或human
和computer
类中引用human
和computer
的成员吗?你想添加表示所用语言的标签吗?对于1,你是说在你的score
课程中引用human
和computer
的成员还是human
和computer
的课程?
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)