简体   繁体   中英

Defining function inside class and using it outside of the class

For a game I am working on I have made a class and within my class I have created a function. However, when I try to call this function outside of the class it shows an error.

The game creates targets using turtle and counts hits and misses when the user clicks the target or the background.

class Application(Frame):
    def __init__(self, master):
        super().__init__(master)

    def deletescore():
        global score
        score -= 1

screen = Screen()
screen.title("Reflex Aim Training")
screen.bgcolor("grey")
screen.onclick(lambda x, y: deletescore())

screen.mainloop()

The game window opens but when I try to click on the window (which would normally count as a miss and take 1 from my score) I recieve an error:

Exception in Tkinter callback
Traceback (most recent call last):
  File "C:\Program Files\Python36\lib\tkinter\__init__.py", line 1699, in __call__
    return self.func(*args)
  File "C:\Program Files\Python36\lib\turtle.py", line 675, in eventfun
    fun(x, y)
  File "I:\My Drive\flowtest.py", line 279, in <lambda>
    screen.onclick(lambda x, y: deletescore())
NameError: name 'deletescore' is not defined

使用Application.deletescore()

Define the function outside the class and then add to it.

class Application(Frame):
    def __init__(self, master):
        super().__init__(master)

def deletescore(self):
    global score
    score -= 1

Application.deletescore = deletescore

Then you can use it. Pay attention to the self parameter. A class method normally operates on the class instance unless used in a "static way" as in this example.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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