Python newbie having problems using classes

Im just starting to get a little confused with classes; however, I ran into a problem.

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

The previous script returns <unbound method MyClass.f> instead of the intended value. How to fix it?

+6
python class
source share
2 answers

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 a specific instance invokes it. Its "unrelated" because you mean f without specifying a particular class, sort of referring to a steering wheel without a car.

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

 x = MyClass() xf() 

(This indicates which instance calls f, so you can refer to instance variables, etc.)

You use f as a static method . These methods are not bound to a specific class and can only refer to their parameters.

The static method will be created and used like this:

 class MyClass(object): def f(): #no self parameter return 'hello world' print MyClass.f() 
+14
source share

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

then use mf() to call the function

Now you may wonder why you do not need to pass a parameter to a function (the "self" parameter). This is because the instance you are calling the function on is actually passed as the first parameter.

That is, MyClass.f(m) is equal to mf() , where m is an instance of the MyClass class.

Good luck

+7
source share

All Articles