簡體   English   中英

這個對象是從哪里來的

[英]where does this object come from

我是一個相對較新的程序員,並且我正在開發游戲。 我正在使用我以前的項目中運行良好的一些代碼。 但是現在,當我嘗試調用某個我不認為需要任何參數的函數時,它將返回一些奇怪的錯誤。

我有從以前的項目中復制的此類:

import pyglet as p


class Button(object):
    def __init__(self, image, x, y, text, on_clicked):
        self._width = image.width
        self._height = image.height
        self._sprite = p.sprite.Sprite(image, x, y)
        self._label = p.text.Label(text,
                                  font_name='Times New Roman',
                                  font_size=20,
                                  x=x + 20, y=y + 15,
                                  anchor_x='center',
                                  anchor_y='center')
        self._on_clicked = on_clicked  # action executed when button is clicked

    def contains(self, x, y):
        return (x >= self._sprite.x - self._width // 2
            and x < self._sprite.x + self._width // 2
            and y >= self._sprite.y - self._height // 2
            and y < self._sprite.y + self._height // 2)

    def clicked(self, x, y):
        if self.contains(x, y):
            self._on_clicked(self)

    def draw(self):
        self._sprite.draw()
        self._label.draw()

我有調用函數的窗口事件(w是窗口):

@w.event
def on_mouse_press(x, y, button, modifiers):
    for button in tiles:
        button.clicked(x, y)

以及它調用的函數的三個變體,每個變體都有不同的“錯誤”:

def phfunc(a):
    print(a)

返回以下內容: <Button.Button object at 0x0707C350>

def phfunc(a):
    print('a')

返回:實際應

def phfunc():
    print('a')

返回一長串的回調,導致以下結果:

  File "C:\Google Drive\game programmeren\main.py", line 15, in on_mouse_press
    button.clicked(x, y)
  File "C:\Google Drive\game programmeren\Button.py", line 25, in clicked
    self._on_clicked(self)
TypeError: phfunc() takes no arguments (1 given)

我最好的猜測是它具有的參數是Button類的self。 這是正確的,我應該為此擔心嗎?

您以self為參數調用self._on_clicked存儲的函數引用。 selfButton類的實例:

self._on_clicked(self)

自定義Button類的默認表示是<Button.Button object at 0x0707C350>

既然您明確地這樣做了,那就不用擔心了。

暫無
暫無

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

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