【问题标题】:Python Unbound Method TypeErrorPython未绑定方法类型错误
【发布时间】:2011-08-26 03:34:43
【问题描述】:

get_pos 方法应该获取用户在条目中输入的内容。当get_pos被执行时,它返回:

TypeError: 未绑定的方法 get_pos() 必须以应用实例作为第一个参数调用(什么都没有)

代码:

class app(object):
    def __init__(self,root):
        self.functionframe=FunctionFrame(root, self)
            self.functionframe.pack(side=BOTTOM)
    def get_pos(self):
        self.functionframe.input(self)
class FunctionFrame(Frame):
    def __init__(self,master,parent):
        Frame.__init__(self,master,bg="grey90")
        self.entry = Entry(self,width=15)
        self.entry.pack
    def input(self):
        self.input = self.entry.get()
        return self.input

【问题讨论】:

  • 输入法的代码在哪里?
  • 这里仍然没有足够的信息。你实际上在哪里调用 get_pos()?
  • get_pos() 绑定到一个按钮,我已经测试了所有绑定都可以正常工作
  • 这里的一个问题是最后一个方法是分配一个与方法(输入)同名的属性,从而使方法消失。未来对 functionframe.input 的引用将获得 self.entry.get() 返回的任何内容。

标签: python methods tkinter


【解决方案1】:

您报告了此错误:

TypeError: unbound method get_pos() must be called with app instance as first argument (什么都没有)

用外行的话来说,这意味着你正在做这样的事情:

class app(object):
    def get_pos(self):
        ...
...
app.get_pos()

你需要做的是这样的:

the_app = app()  # create instance of class 'app'
the_app.get_pos() # call get_pos on the instance

很难比这更具体,因为您没有向我们展示导致错误的实际代码。

【讨论】:

  • 从 Python 3.0 开始:The concept of “unbound methods” has been removed from the language. When referencing a method as a class attribute, you now get a plain function object. 所以这个例子是有效的 Python 3.X 代码,因为没有“未绑定的方法”只是附加到类对象的函数。
  • 是的。我在这里是因为我正在将我的代码库向后移植到 2.7。
【解决方案2】:

我在构造类的实例时忘记在类名中添加括号时遇到了这个错误:

从 my.package 导入 MyClass

# wrong
instance = MyClass

instance.someMethod() # tries to call MyClass.someMethod()

# right
instance = MyClass()


instance.someMethod()

【讨论】:

    【解决方案3】:

    我的水晶球告诉我,您正在使用 app 类(实际上应该称为 App)将 app.get_pos 绑定到一个按钮,而不是创建实例 app_instance = app 并使用 app_instance.get_pos

    当然,正如其他人指出的那样,您发布的代码还有很多其他问题,很难猜测您未发布的代码中的错误。

    【讨论】:

    • 我在发布此代码时尝试重新构建自己的代码,因为原始代码需要很长时间才能调试大约 200 行以及我正在制作的应用程序。
    • 关键是,当您对其进行重组时,您还删除了相关部分,这些部分可以让人们真正能够告诉您问题所在。
    猜你喜欢
    • 2016-04-17
    • 2017-11-06
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2017-07-19
    • 1970-01-01
    • 2016-09-15
    • 2018-04-02
    相关资源
    最近更新 更多