【问题标题】:TypeError: unbound method...instance as first argumentTypeError:未绑定的方法...实例作为第一个参数
【发布时间】:2014-04-15 21:16:22
【问题描述】:

好的,还有一个 TypeError。这是我的代码:

class musssein:      
  def notwendig(self, name):
    self.name = name
    all = []                # fuer jede Eigenschaft eine extra Liste
    day = []
    time = []
    prize = []
    what = []
    kategorie = []
    with open(name) as f:
        for line in f:
            data = line.replace('\n','') #Umbruchzeichen ersetzen
            if data != ' ':             # immer nur bis zur neuen Zeile bzw. bis zum ' ' lesen
                all.append(data)        # in liste einfuegen
            else:
                kategorie.append(all.pop())
                what.append(all.pop())
                prize.append(all.pop())
                time.append(all.pop())
                day.append(all.pop())

def anzeige():
     musssein.notwendig('schreiben.txt')
     print table.Table(
        table.Column('Datum', day),
        table.Column('Kategorie', kategorie),
        table.Column('Was?', what),
        table.Column('Preis', prize, align=table.ALIGN.LEFT))

描述是德语,但它向我解释了您可能已经知道的内容。

当我现在运行 anzeige() 时,终端只显示我:

File "test.py", line 42, in anzeige musssein.notwendig('schreiben.txt') TypeError: unbound method notwendig() must be called with musssein instance as first argument (got str instance instead)

我尝试了很多可能性并阅读了很多其他主题,但我没有找到正确的解释它的主题。

【问题讨论】:

    标签: python class python-2.7 typeerror


    【解决方案1】:

    您的方法“notwendig”希望将 musssein 实例作为其第一个参数,如果在 musssein 实例而不是类本身上调用它,这将透明地完成:

    newinstance=musssein()
    newinstance.notwendig('schreiben.txt')
    

    等价于

    newinstance=musssein()
    musssein.notwendig(newinstance,'schreiben.txt')
    

    此外,您的代码实际上并没有存储文件中的信息,而是存储在方法退出后立即销毁的局部变量中。 您需要将方法更改为:

    def notwendig(self, name):
        self.name = name
        self.all = []                # fuer jede Eigenschaft eine extra Liste
        self.day = []
        self.time = []
        self.prize = []
        self.what = []
        self.kategorie = []
    

    在下一个函数“anzeige”中,需要将它们更改为 newinstance.daynewinstance.kategorie 等,否则您将收到未定义的全局变量错误

    【讨论】:

      【解决方案2】:

      您必须在调用其方法之前创建(实例化)mussein 类的对象

      def anzeige():
          my_var = mussein()
          my_var.notwendig('schreiben.txt')
      

      所以notwendig 方法的self 参数是my_var(mussein 的一个实例)。

      顺便说一下,通常类名必须以大写字母开头。所以在这种情况下应该是Mussein

      【讨论】:

        猜你喜欢
        • 2014-12-10
        • 1970-01-01
        • 2017-05-10
        • 2018-05-10
        • 1970-01-01
        • 1970-01-01
        • 2017-12-09
        • 2015-12-01
        • 2018-08-12
        相关资源
        最近更新 更多