Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
796 views
in Technique[技术] by (71.8m points)

class - Python newbie having a problem using classes

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...