koala421
koala421

Reputation: 816

How do i create a derived class with certain constructors? (python)

This is my class:

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

So far I understand that if I do:

class Human(Player):

It will make Human() a derived class of Player.

What I would like to do is have a constructor playernum inside this class. Then take the overridden play_turn and print a player number(ie. playernum)...I just want to know how this would be implemented... do I repeat

def play_turn(self,board):

inside the Human class or do I simply put

class Human(Player):
    play_turn

and inside the

play_turn(self,board):
    "put"
    print playernum

I'm kind of new to derivations of classes and the logic behind it. Any input will be highly appreciated. Thanks.

Upvotes: 1

Views: 121

Answers (1)

Josh Bothun
Josh Bothun

Reputation: 1344

You're correct that to override a method from a parent class, you 'repeat' the method inside the derived class. Your code should end up looking something like:

class Human(Player):
    def play_turn(self, board):
        print self.playernum

If play_turn is meant to contain shared logic for its derived classes, you want to call the parents' method first:

class Human(Player):
    def play_turn(self, board):
        super(Human, self).play_turn(board)
        print self.playernum

Upvotes: 4

Related Questions