6

Im just beginning to mess around a bit with classes; however, I am running across a problem.

class MyClass(object):
 def f(self):
 return 'hello world'
print MyClass.f

The previous script is returning <unbound method MyClass.f> instead of the intended value. How do I fix this?

SilentGhost
322k67 gold badges312 silver badges294 bronze badges
asked Feb 9, 2010 at 21:43
2
  • 3
    What tutorial are you reading? Where did you see code like this? Commented Feb 9, 2010 at 23:29
  • I was reading from a textbook, however, it was pretty vague about the code and didn't provide a simple example. So I just fiddled around and tried to get something to work. Commented Feb 10, 2010 at 18:38

2 Answers 2

13

MyClass.f refers to the function object f which is a property of MyClass. In your case, f is an instance method (has a self parameter) so its called on a particular instance. Its "unbound" because you're referring to f without specifying a specific class, kind of like referring to a steering wheel without a car.

You can create an instance of MyClass and call f from it like so:

x = MyClass()
x.f()

(This specifies which instance to call f from, so you can refer to instance variables and the like.)

You're using f as a static method. These methods aren't bound to a particular class, and can only reference their parameters.

A static method would be created and used like so:

class MyClass(object):
 def f(): #no self parameter
 return 'hello world'
print MyClass.f()
answered Feb 9, 2010 at 21:47
Sign up to request clarification or add additional context in comments.

Comments

6

Create an instance of your class: m = MyClass()

then use m.f() to call the function

Now you may wonder why you don't have to pass a parameter to the function (the 'self' param). It is because the instance on which you call the function is actually passed as the first parameter.

That is, MyClass.f(m) equals m.f(), where m is an instance object of class MyClass.

Good luck!

S.Lott
393k83 gold badges521 silver badges791 bronze badges
answered Feb 9, 2010 at 21:44

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.