[FIXED] Probelm with implementing a method inside of another method. Python OOP

Issue

This is my code. It is the main class of a Dictionary program. All the values that it has correspond to either commands that I want to execute as soon as the program starts, or constants that I save as values for the class

class GameDictionary(object):
     def __init__(self):
            pygame.init()
            game_display.fill(white)
            self.game_display = pygame.display.set_mode((window_width,window_height))
            self.fontBig  = pygame.font.Font('HanaMinA.ttf', 400)
            self.fontMedium = pygame.font.Font('HanaMinA.ttf', 75)
            self.fontSmall   = pygame.font.Font('HanaMinA.ttf', 50)
            self.fontFurigana = pygame.font.Font('HanaMinA.ttf', 25)
            self.kanji = 0
            
    def test(self,variable):
        print(str(self.kanji) + str(variable))
    def run(self):
        GameDictionary.test(GameDictionary(),"TEXT")

Why does it make me call GameDictionary() inside the run method? Shouldn't I be able to run the method without needing to reference the class?

Without it I get a call error


Solution

Because test is a method of GameDictionary instances, and you called it on the class, not the instance. A simpler equivalent run would be:

def run(self):
    GameDictionary().test("TEXT")
    #             ^^ parens make it construct a GameDictionary instance to call on

or, given run itself is an instance method, so you have an instance already (self), just do:

def run(self):
    self.test("TEXT")

and avoid constructing a fresh instance at all.



Answered By - ShadowRanger
Answer Checked By - Dawn Plyler (Python.Easybugfix Volunteer)

Related Posts

Post a Comment