这是我的课:
class Player(object):
def __init__(self, playernum):
self.playernum = playernum
def play_turn(self, board):
"""This method is passed an instance of ConnectFour.
It should examine the board (using methods on the ConnectFour class...
assume you have it) and eventually call board.play_turn and return"""
pass
到目前为止,我明白如果我这样做:
class Human(Player):
它将使 Human() 成为 Player 的派生类。
我想做的是在这个类中有一个构造函数 playernum。然后采用覆盖的 play_turn 并打印一个玩家编号(即 playernum)...我只想知道这将如何实现...我要重复吗
def play_turn(self,board):
在 Human 类中还是我简单地说
class Human(Player):
play_turn
和里面
play_turn(self,board):
"put"
print playernum
我对类的派生及其背后的逻辑有点陌生。任何输入将不胜感激。谢谢。
最佳答案
你是正确的,要覆盖父类的方法,你在派生类中“重复”该方法。您的代码最终应该看起来像这样:
class Human(Player):
def play_turn(self, board):
print self.playernum
如果 play_turn
旨在包含其派生类的共享逻辑,您需要先调用父类的方法:
class Human(Player):
def play_turn(self, board):
super(Human, self).play_turn(board)
print self.playernum
关于python - 如何使用某些构造函数创建派生类? (Python),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15419196/