Michael Johnson Michael Johnson - 1 year ago 64
Python Question

Method inheritance issue

When I attempt to create a 'BJ_player' object:

player = BJ_player(name, number_chips)

I receive:

TypeError: init() takes exactly 2 positional arguments (3 given).

I've used the same methodology to inherit from 'BJ_Hand' as I did to inherit from 'Hand'.

Could someone please explain?

This first class is located in 'cardsmodule':

class Hand(object):
"""A hand of playing cards"""
def __init__(self):
self.cards = []

def __str__(self):
if self.cards:
rep = ""
for card in self.cards:
rep += str(card) + "\t"
rep = "<empty>"
return rep

class BJ_hand(cardsmodule.Hand):
"""A BlackJack hand"""

def __init__(self, name):
super(BJ_hand, self).__init__()
self.name = name

def __str__(self):
rep = self.name + "\t" + super(BJ_hand,self).__str__()
if self.total:
rep += "(" + str(self.total) + ")"
return rep

class BJ_player(BJ_hand):
"""A BlackJack player"""
def __init__(self, number_chips):
super(BJ_player, self).__init__()
#self.name = name
self.number_chips = number_chips

def __str__(self):
rep = self.name + " has " + str(self.number_chips) + " chips.\n"
rep += super(BJ_player, self).__init__()

Answer Source

You defined an __init__ method that only takes one argument (plus self):

class BJ_player(BJ_hand):
    """A BlackJack player"""
    def __init__(self, number_chips):
        #              ^^^^^^^^^^^^

There is no parameter for name, but you are trying to pass that in:

player = BJ_player(name, number_chips)
#                  ^^^^  ^^^^^^^^^^^^

Python doesn't look to all base __init__ methods for you; it'll only 'see' BJ_player. If you wanted to pass in a name value for BJ_hand.__init__, then BJ_player.__init__() must accept that as an argument. You can then pass it on via the super().__init__() call:

class BJ_player(BJ_hand):
    """A BlackJack player"""
    def __init__(self, name, number_chips):
        super(BJ_player, self).__init__(name)

Note how the name parameter from the method is now passed on in the chain.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download