1

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

2
  • For the instances in WOFPlayer which you would not like to be inherited in WOFComputerPlayer, you can set them as private instances. To do so, just put two underlines before the name of the instances. For example, __name. Commented Sep 5, 2020 at 6:47
  • Well, if WOFComputerPlayer.__init__ is supposed to accept both name and difficulty as parameters, then the first thing is that they should both appear between the parentheses that appear after def __init__. Otherwise, I don't see what the actual question is. Commented Sep 5, 2020 at 7:02

2 Answers 2

2

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.