Python Forum
Calling a base class variable from an inherited class - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Calling a base class variable from an inherited class (/thread-36129.html)



Calling a base class variable from an inherited class - CompleteNewb - Jan-19-2022

I have this little program

class Generic_Player: def __init__(self): self.hit = True def Bust(self): print(self.name + " busts.") class Player(Generic_Player): def __init__(self, name): self.name = name def Win(self): print(self.name + " wins!") def Lose(self): print(self.name + " loses.") player1 = Player("player1") player1.Bust() print(player1.hit)
which gives me this error

Error:
Traceback (most recent call last): File "/usr/lib/python3.8/idlelib/run.py", line 559, in runcode exec(code, self.locals) File "/home/fook/Documents/pygame/opencv/test.py", line 43, in <module> print(player1.hit) AttributeError: 'Player' object has no attribute 'hit'
Since player1 is inherited from Generic_Player, True should be printed, no?


RE: Calling a base class variable from an inherited class - bowlofred - Jan-19-2022

You have to have your init call the base class init.

class Player(Generic_Player): def __init__(self, name): super().__init__() self.name = name



RE: Calling a base class variable from an inherited class - deanhystad - Jan-19-2022

A subclass needs to call the __init__() method(s) of its superclass(es) to so they can initialize their instance variables. In this case Player.__init__() does not call GenericPlayer.__init__(). Since GenericPlaier.__init__() was never called this code was never executed:
 self.hit = True
self.hit is never assigned, so there is no "hit" attribute in player1.

To call the superclass __init__() you should use the super().__init__(self) as recommended by bowlofred. Sometimes you will see this done using the superclass name explicitly.
class Player(Generic_Player): def __init__(self, name): GenericPlayer.__init__(self) self.name = name



RE: Calling a base class variable from an inherited class - CompleteNewb - Jan-20-2022

oh okay thanks greatly appreciated


This forum uses Lukasz Tkacz MyBB addons.
Forum use Krzysztof "Supryk" Supryczynski addons.