【问题标题】:where does this object come from这个对象来自哪里
【发布时间】:2013-03-13 09:24:46
【问题描述】:

我是一个相对较新的程序员,我正在制作游戏。我正在使用我以前的项目中运行良好的一些代码。但是现在当我尝试调用某个我认为不需要任何参数的函数时,它会返回一些奇怪的错误。

我有这个类,我从我以前的项目中复制过来的:

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)

返回这个东西:&lt;Button.Button object at 0x0707C350&gt;

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 在对象上调用方法时被隐式传递。

标签: python object


【解决方案1】:

您使用self 作为参数调用存储在self._on_clicked 中的函数引用。 self 是您的 Button 类的实例:

self._on_clicked(self)

您的自定义Button 类的默认表示是&lt;Button.Button object at 0x0707C350&gt;

既然你明确地这样做了,那就不用担心了。

【讨论】:

    猜你喜欢
    • 2017-06-04
    • 2021-11-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-01
    • 2018-05-26
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多