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)

そして、それぞれが異なる「エラー」を持つ、それが呼び出す関数の 3 つのバリエーション:

def phfunc(a):
    print(a)

このことを返します:<Button.Button object at 0x0707C350>

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

戻り値: 実際に必要な 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 クラスの自己であるということです。これは正しいですか、これについて心配する必要がありますか?

4

1 に答える 1

1

に格納されている関数参照をパラメーターとして呼び出しself._on_clickedますself。あなたのクラスselfのインスタンスです:Button

self._on_clicked(self)

カスタムButtonクラスのデフォルトの表現は<Button.Button object at 0x0707C350>.

明示的に行ったので、心配する必要はありません。

于 2013-03-23T15:55:08.680 に答える