简体   繁体   English

为什么我不能从python类中调用我的方法?

[英]why can't I call my method from within class in python?

I am trying to make a button class for my game, using pygame. 我正在尝试使用pygame为我的游戏制作一个按钮类。 But in the button class, I cannot call methods that are contained in the class itself. 但是在按钮类中,我无法调用类本身包含的方法。

I am new to classes so I may be missing something important, I'm sorry 我刚上课,所以我可能错过了一些重要的东西,对不起

I tried to add self to the isHovering() Method but it still doesn't work. 我试图将self添加到isHovering()方法中,但仍然无法正常工作。

import pygame

class Button():
    def __init__(self, pos, value, img, screen):
        self.pos = pos
        self.value = value
        self.img = img
        self.screen = screen

    ### Getters and Setters ###===============
    ### Get/Set Value : True/False ###
    def setValue(self, value):
        self.value = value
    def getValue(self):
        return self.value

    ### Get/Set Pos ###
    def setPos(self, pos):
        self.pos = pos
    def getPos(self):
        return self.pos

    ### Get/Set Img ###
    def setImg(self, img):
        self.img = img
    def getImg(self):
        return self.img

    #==========================================

    def isHovering(self):
        pos = getPos()
        imgRect = pygame.rect(pos[0], pos[1], 105, 105)
        if imgRect.collidepoint(pygame.mouse.get_pos()):
            return True
        else:
            return False

    def update(self, screen):
        if isHovering():
            image = pygame.transform.scale(self.img(95, 95))
        else:
            image = pygame.transform.scale(self.img(105, 105))
        screen.blit(image, self.pos)

I thought that when update(screen) was called in my main loop, that it would call isHovering(), and return a True or False, but instead I get this error: 我以为在我的主循环中调用update(screen)时,它将调用isHovering()并返回True或False,但我却收到此错误:

NameError: name 'isHovering' is not defined NameError:名称“ isHovering”未定义

In def update(self, screen) , The if statement should be if self.isHovering() . def update(self, screen) ,if语句应为if self.isHovering()

If not, the interpreter will look for a isHovering function somewhere in the current module, like if you had defined it outside your class. 如果不是,解释器将在当前模块中的某个位置寻找isHovering函数,就像您在类之外定义它一样。 Using the self. 使用self. prefix will indicate that you are indeed trying to call a method of the instance as JacoblRR already pointed out in a comment. 前缀将表明您确实在尝试调用实例的方法,正如JacoblRR在注释中已经指出的那样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM