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


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>
  TypeError: unbound method f() must be called with fibo instance 
  as first argument (got nothing instead)

Code: (swineflu.py)

class fibo:

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

Script 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?

11/6/2014 9:07:25 PM

Accepted Answer

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.

12/17/2010 5:58:59 PM

How to reproduce this error with as few lines as possible:

>>> class C:
...   def f(self):
...     print "hi"
>>> C.f()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unbound method f() must be called with C instance as 
first argument (got nothing instead)

It fails because of TypeError because you didn't instantiate the class first, you have two choices: 1: either make the method static so you can run it in a static way, or 2: instantiate your class so you have an instance to grab onto, to run the method.

It looks like you want to run the method in a static way, do this:

>>> class C:
...   @staticmethod
...   def f():
...     print "hi"
>>> C.f()

Or, what you probably meant is to use the instantiated instance like this:

>>> class C:
...   def f(self):
...     print "hi"
>>> c1 = C()
>>> c1.f()
>>> C().f()

If this confuses you, ask these questions:

  1. What is the difference between the behavior of a static method vs the behavior of a normal method?
  2. What does it mean to instantiate a class?
  3. Differences between how static methods are run vs normal methods.
  4. Differences between class and object.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow