Home > Blockchain >  Why isn't my subclass inheriting a method from the superclass?
Why isn't my subclass inheriting a method from the superclass?

Time:06-23

In a blackjack game I have the following piece of code:

class Hand(object):
    def __init__(self):
        self.hand = []
        
        
    def hand_score(self):
        ...
    
    
class Dealer(object):
    def __init__(self):
        Hand.__init__(self)

Where hand_score() should calculate the score in self.hand and return it's value. However when I assign dealer = Dealer(), deal the cards and call dealer.hand_score() it gives me the error AttributeError: 'Dealer' object has no attribute 'hand_score'. The self.hand value is inherited and works as expected when I call dealer.hand.

CodePudding user response:

You aren't actually inheriting from Hand; you are just inappropriately using Hand.__init__ to initialize an unrelated instance.

Hand has to be listed as a base class in the class definition.

class Dealer(Hand):
    def __init__(self):
        Hand.__init__(self)  # preferably, super().__init__()

CodePudding user response:

This:

class Dealer(object):

should be:

class Dealer(Hand):

Otherwise your class will only sub-class the 'object' class.

  • Related