简体   繁体   English

有关Python继承的面向对象设计

[英]Object Oriented Design concerning inheritance in Python

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)

My problem is with the add_score method in the Score class. 我的问题是Score类中的add_score方法。

In Python context: 在Python上下文中:

Since both human and computer are inherited from the Player class (they have their own methods, but omitted in this question), how can I refer either of them in the add_score method? 由于human computer都从Player类继承(它们有自己的方法,但在本问题中省略了),我如何在add_score方法中引用它们中的add_score (To be clear: I want to say add_score to any object inherited from the Player class. [Does it matter if meant “ add_score to any object either from the Player class or to any object inherited from the Player class”?]) (要明确:我想对从Player类继承的任何对象说add_score 。[意思是“对从Player类继承的任何对象还是对从Player类继承的任何对象的add_score意义?”)

Well, you're using python in your example and so there are a few answers to this question. 好吧,您在示例中使用的是python,因此此问题有一些答案。 There is the OOP way of doing this and then there is the pythonic way of doing this. 有一种执行此操作的OOP方法,然后有一种执行此操作的pythonic方法。

The OOP way of doing this is that your __str__ (python's version of ToString ) would be abstract (or otherwise implemented generically) and you'd override that in the derived class. OOP的实现方式是__str__ToString python版本)将是抽象的(或以其他方式通用实现),并且您将在派生类中重写它。 Though, truthfully, you'd not use ToString -- you'd define an abstract method for this purpose specifically. 虽然,实际上,您不会使用ToString -专门为此目的定义了一个抽象方法。 Perhaps PrintScore . 也许是PrintScore

That said, your usage of OOP in this example isn't great either. 也就是说,您在此示例中对OOP的使用也不是很好。 Does the ComputerPlayer and HumanPlayer have different implementations resulting in the need of derived classes? ComputerPlayerHumanPlayer是否具有不同的实现,从而导致需要派生类? Given your example (and perhaps you have plans for more), you don't. 给出您的示例(也许您有更多计划),您没有。 You could just use a Player Class and make a property " IsAI ". 您可以只使用Player类并设置属性“ IsAI ”。 Set that for true for a computer player and false for human player. 对于计算机播放器,将其设置为true;对于人工播放器,将其设置为false。

I don't mean for this to sound critical so please don't take it that way. 我并不是说听起来很关键,所以请不要那样做。 I simply mean to provide some guidance. 我只是想提供一些指导。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM