【问题标题】:Cause of Python type error 'unbound method'?Python类型错误“未绑定方法”的原因?
【发布时间】:2016-04-17 13:49:24
【问题描述】:

我对 Python 很陌生,很抱歉,如果我很讨厌,但是每当我尝试我的代码时,我都会收到这个错误,错误如下:

Traceback (most recent call last):<br>
  File "<pyshell#3>", line 1, in <module>
    fopen.open_file()
TypeError:<br> unbound method open_file() must be called with openFile instance as first argument (got nothing instead)

程序的目的是读入用户输入的文件。

这是我的代码:

class openFile:
    def file_to_open():
        fopen = raw_input('Enter the file path : ')
        open_file = open(fopen)
        print open_file

【问题讨论】:

  • 你为什么要使用类?
  • 引发的异常与您的代码不对应。
  • 你是如何使用那个类来创建你的实例的?

标签: python function python-2.7 class methods


【解决方案1】:

我认为您的意思是将 file_to_open 定义为类 openFile 的成员函数,对吧?如果是这样,那么您应该将“self”作为参数:

def file_to_open(self):
 ...

你应该这样称呼它:

f = openFile()
f.file_to_open()

也就是说,我认为您应该重新考虑在这里使用类。相反,您可以只定义一个函数

def open_a_file():
  filename = raw_input('Enter the file path : ')
  return open(filename)

【讨论】:

    猜你喜欢
    • 2011-08-26
    • 2018-08-12
    • 2017-11-06
    • 1970-01-01
    • 2016-11-30
    • 2020-02-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多