Python新手有使用类的问题 [英] 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
< unbound method MyClass.f>
而不是预期值。如何解决此问题?
The previous script is returning <unbound method MyClass.f>
instead of the intended value. How do I fix this?
推荐答案
MyClass.f
函数对象f,它是MyClass的一个属性。在你的情况下,f是一个实例方法(有一个自我参数),所以它在一个特定的实例上调用。它的未绑定,因为你指的是f而没有指定一个特定的类,有点像是指没有汽车的方向盘。
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.
你可以创建一个实例MyClass,并从中调用f:
You can create an instance of MyClass and call f from it like so:
x = MyClass()
x.f()
(这指定从哪个实例调用f,所以可以参考实例变量等)
(This specifies which instance to call f from, so you can refer to instance variables and the like.)
您使用f作为静态方法
。这些方法不绑定到一个特定的类,只能引用它们的参数。
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()
这篇关于Python新手有使用类的问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!