Home>

About how to write python classes.
I make RPG while referring to the website.
So, I tried to make a class about the title screen, but an error appears.
This is what I wrote

class Title:
    """title screen"""
    START, CONTINUE, EXIT = 0, 1, 2
    def __init __ (self):
        self.myfont = pygame.font.Font ('ipag.ttf', 40)
        self.title_img = load_image ("data", "python_quest.png", -1)
        self.cursor_img = load_image ("data", "cursor2.png", -1)
        self.menu = self.START
    def moji (self):
        self.moji1 = self.myfont.render ('START', True, (0,0,0))
        self.moji2 = self.myfont.render ('CONTINUE', True, (0,0,0))
        self.moji3 = self.myfont.render ('EXIT', True, (0,0,0))
    def update (self):
        pass
    def draw (self, screen):
        screen.fill ((0,0,128))
        # Draw title
        screen.blit (self.title_img, (20,60))
        # Draw menu
        screen.blit (self.moji1, (260,240))
        screen.blit (self.moji2, (260,280))
        screen.blit (self.moji3, (260,320))
        # Draw menu cursor
        if self.menu == self.START:
            screen.blit (self.cursor_img, (240, 240))
        elif self.menu == self.CONTINUE:
            screen.blit (self.cursor_img, (240, 280))
        elif self.menu == self.EXIT:
            screen.blit (self.cursor_img, (240, 320))


This is the error code.

  

AttributeError:'Title'object has no attribute'moji1'

I think you will get the same error on other moji2 and moji3.

I'm trying to run

  • Load font file
  • Creating the title text using it is.

I don't understand the class system, so it seems strange.
I would be grateful if you could tell me how to handle this error.

  • Answer # 1

    If you put

    moji ()in__ init __ (), I think it will work for the time being.

    class Title:
        """title screen"""
        START, CONTINUE, EXIT = 0, 1, 2
        def __init __ (self):
            self.myfont = pygame.font.Font ('ipag.ttf', 40)
            self.title_img = load_image ("data", "python_quest.png", -1)
            self.cursor_img = load_image ("data", "cursor2.png", -1)
            self.menu = self.START
            self.moji1 = self.myfont.render ('START', True, (0,0,0))
            self.moji2 = self.myfont.render ('CONTINUE', True, (0,0,0))
            self.moji3 = self.myfont.render ('EXIT', True, (0,0,0))
    ...

  • Answer # 2

    When creating a variable with self, you may define it ininit(self).
    I think other functions can be accessed but not defined.
    Reference site