Maxiboi
Maxiboi

Reputation: 160

Python class method inheritance

I have 2 classes, one inherits from the other. I need instances of WOFPlayer to take 1 required parameter - name, 2 optional and instances of WOFComputerPlayer to take 2 required parameters - name and difficulty and 2 optional as in the WOFPlayer. How do I do that?

Here's what I have tried

class WOFPlayer:
    def __init__(self, name, prizeMoney = 0, prizes = []):
        self.name = name
        self.prizeMoney = prizeMoney
        self.prizes = prizes[:]

class WOFComputerPlayer(WOFPlayer):
    def __init__(self, difficulty):
        WOFPlayer.__init__(self, name, prizeMoney = 0, prizes = [])
        self.difficulty = difficulty

Thanks in advance

Upvotes: 1

Views: 225

Answers (2)

Prayson W. Daniel
Prayson W. Daniel

Reputation: 15588

You are closer than you think.


class WOFPlayer:
    def __init__(self, name, prizeMoney=0, prizes=None):
        
        self.name = name
        self.prizeMoney = prizeMoney

        if prizes is None:
            prizes = []
        self.prizes = prizes[:]

class WOFComputerPlayer(WOFPlayer):
    def __init__(self, name, difficulty, prizeMoney=0, prizes=None):
        super().__init__(name, prizeMoney, prizes)
        self.difficulty = difficulty

Note that I replaced passing a mutable value as a default argument. [] as default argument will mutate anytime that value is mutated, which can be a recipe for a bug. But the rest of the code is yours.

Upvotes: 2

Algebra8
Algebra8

Reputation: 1365

I need instances of WOFPlayer to take 1 required parameter - name, 2 optional

I would strongly suggest you don't use a mutable object (the list in this case) as a default argument. Here's why.

and instances of WOFComputerPlayer to take 2 required parameters - name and difficulty and 2 optional as in the WOFPlayer

You need to pass in the values from WOFComputerPlayer to its base class. That is, pass in name to WOFComputerPlayer.

class WOFComputerPlayer(WOFPlayer):
    def __init__(self, name, difficulty, prize_money=0, prizes=None):
        WOFPlayer.__init__(self, name, prizeMoney=prize_money, prizes=prizes)
        self.difficulty = difficulty

Upvotes: 2

Related Questions