0

I have the following classes for a game of black jack.

class Player:
    
    def __init__(self, player, balance=0): 
        self.player = player
        self.balance = balance
        
    def __str__(self):
        return f'Player:   {self.player}\n Balance:  ${self.balance}'
        
    def bet(self):
        print(self.balance)


class Dealer(Player):
    
    def __init__(self):    
        pass

I am trying to call the bet method from Player class through the Dealer class but am getting the following error when I print(self.balance).

AttributeError: 'Dealer' object has no attribute 'balance'

I changed this to print(Player.balance) but this does not work either. Can someone please point me in the right direction?

name = input("Enter your full name:        ")   
balance =int(input("Enter the amount you would like to place on the table?  "))
    
my_player = Player(name, balance)    


my_dealer = Dealer() 
my_dealer.bet()
Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
unaied
  • 197
  • 11
  • 2
    `__init__` of `Dealer` overridden the `__init__` of `Player` class – Moinuddin Quadri Jan 14 '21 at 13:09
  • AttributeError: 'Dealer' object has no attribute 'balance' – unaied Jan 14 '21 at 13:10
  • 1
    Because `Dealer`'s `__init__()` doesn't initialise `self.balance`, that attribute doesn't exist. You need to either not provide a `__init__()` method on `Dealer` (so `Player`'s __init__ is used, i.e. you have to provide player and option balance), or `Dealer`'s __init__() needs to have parameters which call super().__init__() with those params. – DisappointedByUnaccountableMod Jan 14 '21 at 13:10
  • 2
    Does this answer your question? [What does 'super' do in Python?](https://stackoverflow.com/questions/222877/what-does-super-do-in-python) – costaparas Jan 14 '21 at 13:10
  • If your dealer doesn't have a balance, consider having it not be a subclass of player. – khelwood Jan 14 '21 at 13:12
  • @unaied Try to always provide errors in the question itself by [editing](https://stackoverflow.com/posts/65719539/edit) it. – Ted Klein Bergman Jan 14 '21 at 13:12

2 Answers2

3

Python doesn't automatically call __init__ for super classes. You need to call super in your Dealer class

class Dealer(Player):
    def __init__(self):
        super().__init__(..., ...)
...

In your case, you're not using the Dealer's __init__ so you can remove it completely, in which case it'll inherit its super implementation anyway.

Holloway
  • 6,412
  • 1
  • 26
  • 33
1

Nice works bro! You just miss a little thing when you inherit a class. At __init__ method, you need to pass a statement: super().__init__(...). In (...), you have to pass all the attributes of the parent class have. After that, you can call the attributes and methods of the parent class.

Ted Klein Bergman
  • 9,146
  • 4
  • 29
  • 50
Halley
  • 11
  • 3