簡體   English   中英

在類內部定義函數並在類外部使用它

[英]Defining function inside class and using it outside of the class

對於游戲,我正在制作一個類,並且在我的類中創建了一個函數。 但是,當我嘗試在類之外調用此函數時,將顯示錯誤。

該游戲使用烏龜創建目標,並在用戶單擊目標或背景時計算命中率和未命中率。

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()

游戲窗口打開,但是當我嘗試單擊窗口時(通常算作未命中並從我的得分中減去1),我收到一個錯誤:

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()

在類之外定義函數,然后添加到其中。

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

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

Application.deletescore = deletescore

然后就可以使用它了。 注意self參數。 除非在此示例中以“靜態方式”使用,否則類方法通常在類實例上運行。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM