2013-03-23 112 views
0

我是一個相對較新的程序員,我正在製作一款遊戲。我使用我以前的項目中運行良好的代碼。但是現在當我嘗試調用某個函數時,我不認爲應該需要任何參數,它會返回一些奇怪的錯誤。此對象來自哪裏

我有這個類,我從我以前的項目複製:

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類的自我。這是正確的,我應該擔心這個嗎?

+2

當您調用對象上的方法時,會自動傳遞'self'。 – 2013-03-23 15:48:23

回答

1

您可以使用self作爲參數調用存儲在self._on_clicked中的函數引用。 self是你Button類的實例:

self._on_clicked(self) 

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

由於您明確地這樣做過,所以不必擔心。