未绑定的方法f()必须以fibo_实例作为第一个参数来调用(取而代之的是class classobj实例) [英] unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

查看:94
本文介绍了未绑定的方法f()必须以fibo_实例作为第一个参数来调用(取而代之的是class classobj实例)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中,我试图在类中运行方法,但出现错误:

In Python, I'm trying to run a method in a class and I get an error:

Traceback (most recent call last):
  File "C:\Users\domenico\Desktop\py\main.py", line 8, in <module>
    fibo.f()
  TypeError: unbound method f() must be called with fibo instance 
  as first argument (got nothing instead)

代码:(swineflu.py)

Code: (swineflu.py)

class fibo:
    a=0
    b=0

    def f(self,a=0):
        print fibo.b+a
        b=a;
        return self(a+1)

脚本main.py

import swineflu

f = swineflu
fibo = f.fibo

fibo.f()            #TypeError is thrown here

此错误是什么意思?是什么导致此错误?

What does this error mean? What is causing this error?

推荐答案

好的,首先,您不必使用其他名称来引用模块;您已经有一个引用(来自import),您可以使用它.如果您想使用其他名称,请使用import swineflu as f.

OK, first of all, you don't have to get a reference to the module into a different name; you already have a reference (from the import) and you can just use it. If you want a different name just use import swineflu as f.

第二,您获得的是对该类的引用,而不是实例化该类.

Second, you are getting a reference to the class rather than instantiating the class.

所以应该是:

import swineflu

fibo = swineflu.fibo()  # get an instance of the class
fibo.f()                # call the method f of the instance

绑定方法是附加到对象实例的方法. 未绑定方法当然是附加到实例的方法.该错误通常表示您是在类而不是实例上调用方法,这正是在这种情况下发生的事情,因为您尚未实例化该类.

A bound method is one that is attached to an instance of an object. An unbound method is, of course, one that is not attached to an instance. The error usually means you are calling the method on the class rather than on an instance, which is exactly what was happening in this case because you hadn't instantiated the class.

这篇关于未绑定的方法f()必须以fibo_实例作为第一个参数来调用(取而代之的是class classobj实例)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆