PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, July 7, 2022

[FIXED] Why isn't my subclass inheriting a method from the superclass?

 July 07, 2022     class, inheritance, python, subclass, superclass     No comments   

Issue

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.


Solution

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__()


Answered By - chepner
Answer Checked By - Mary Flores (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing