1

I was going to Calling a function of a module from a string with the function's name in Python but whenever i call my class in my program it gives me this error:TypeError: unbound method bar() must be called with foo instance as first argument (got nothing instead)

Can someone help me

Community
  • 1
  • 1
user928968
  • 47
  • 3
  • Really need to see the code to be sure, but it sounds like you are calling a member of a class, without the method being a [classmethod](http://docs.python.org/library/functions.html#classmethod). – Chris Pickett Aug 25 '11 at 14:13

2 Answers2

9

Here is a typical situation which produces the problem you describe.

class Foo(object):
    def bar(self,x):
        print(x)

foo=Foo()

Calling gettatrr(Foo,'bar') returns the unbound method, Foo.bar.

getattr(Foo,'bar')(1)

results in

TypeError: unbound method bar() must be called with Foo instance as first argument (got int instance instead)

The method, Foo.bar, is called "unbound" because no instance (such as foo) is going to be supplied as the first argument when called. After all, how could it when only the class Foo was supplied?

On the other hand, if you supply an instance of the class:

getattr(foo,'bar')(1)

yields

1

since foo.bar is a "bound" method -- foo will be supplied as the first argument when foo.bar is called.

PS. Your error message says, "...called with foo instance ...". Compared with the error message I posted above, it appears your class is called lowercased foo. Note that the PEP8 style guide recommends always naming classes with a capital letter, and instances with a lowercase one. Doing so will help you avoid this error.

cwallenpoole
  • 72,280
  • 22
  • 119
  • 159
unutbu
  • 711,858
  • 148
  • 1,594
  • 1,547
1

Let's take this example:

class Foo:
  def bar(self):
    print 'bar'
  @classmethod
  def baz(cls):
    print 'baz'
  @staticmethod
  def qux():
    print 'qux'

def quux():
  print 'quux'
Foo.quux = quux  # note: Foo.quux is a function attribute NOT a method

Then you can have different measures of success depending on how you call these:

f = Foo()
f.bar()  # works
getattr(f, 'bar')()  # works
getattr(Foo, 'bar')()  # TypeError
getattr(Foo, 'bar')(f)  # works
f.baz()  # works
getattr(f, 'baz')()  # works
getattr(Foo, 'baz')()  # works

And so on. The basic idea at play is that when calling a method, using the syntax obj.method(...), the object itself is passed as the first self argument; but when the same callable is addressed as an attribute of the class, then this special substitution is not done. This applies to the getattr function also.

wberry
  • 16,119
  • 7
  • 48
  • 79