2015-11-13 60 views
1
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中继承的面向对象设计

在Python方面:

由于两个humancomputerPlayer类继承的(他们有自己的方法,但在这个问题上省略),我怎么可以指他们在add_score方法? (需要明确的是:我想说add_scorePlayer类继承的任何对象[不要紧,如果指的是“add_score任何对象无论是从Player类或从Player类继承的任何对象”?])

+1

是否要添加代表使用语言的标签? – Marged

+0

对于1,你说的是在你的'score'类或'human'和'computer'类中引用'human'和'computer'的成员吗? –

回答

0

那么,你在你的例子中使用python,所以这个问题有几个答案。有OOP这样做的方式,然后有pythonic这样做的方式。

这样做的OOP方式是你的__str__(python的版本ToString)将是抽象的(或以其他方式实现),你会覆盖派生类中的。尽管如此,你不会使用ToString - 你会为此专门定义一个抽象方法。也许PrintScore

也就是说,在这个例子中你对OOP的使用也不是很好。 ComputerPlayerHumanPlayer是否有不同的实现,导致需要派生类?鉴于你的例子(也许你有更多的计划),你不会。您可以使用Player类别并创建属性“IsAI”。为电脑播放器设置为true,为人类播放器设置为false。

我并不是说这听起来很重要,所以请不要这样说。我只是想提供一些指导。