unbound method f() must be called with fibo_ instance as first argument (got classobj instance instead)

前端 未结 8 1757
隐瞒了意图╮
隐瞒了意图╮ 2020-11-28 23:42

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\"         


        
相关标签:
8条回答
  • 2020-11-29 00:12

    f is an (instance) method. However, you are calling it via fibo.f, where fibo is the class object. Hence, f is unbound (not bound to any class instance).

    If you did

    a = fibo()
    a.f()
    

    then that f is bound (to the instance a).

    0 讨论(0)
  • 2020-11-29 00:16

    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.

    So this should be:

    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.

    0 讨论(0)
提交回复
热议问题