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

Maxiboi
  • 150
  • 1
  • 8
  • 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```. – Liana Sep 05 '20 at 06: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. – Karl Knechtel Sep 05 '20 at 07:02

2 Answers2

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
Algebra8
  • 1,115
  • 1
  • 10
  • 23
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.

Prayson W. Daniel
  • 14,191
  • 4
  • 51
  • 57