Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/oop/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python中关于继承的面向对象设计_Python_Oop - Fatal编程技术网

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)