Python类属性引用 [英] Python class attribute referencing
问题描述
这是我从python类教程中找到的示例代码。
class MyClass:
i = 12345
def f(self):
return'hello world'
print MyClass.f
print MyClass.i
一旦我运行这个,我期待hello world和12345的输出结果。但我得到这个
>>>
< unbound method MyClass.f>
12345
>>>>
为什么它不给我'hello world'?如何更改我的代码,以便它将打印出hello world? PS我没有关于python类和方法的线索,只是开始学习。
首先创建一个MyClass的实例。 >
test = MyClass()
print test.f()
print MyClass.i
您不需要创建MyClass for i的实例,因为它是一个类成员,而不是实例成员。 / p>
This is a sample code that i found from one of the python class tutorial.
class MyClass:
i = 12345
def f(self):
return 'hello world'
print MyClass.f
print MyClass.i
Once i run this, i am expecting the output result of "hello world" and "12345". But instead i am getting this
>>>
<unbound method MyClass.f>
12345
>>>
why is it not giving me 'hello world'? How do i change my code so that it will print out "hello world"? P.S i have no clue about python classes and methods and just started learning.
Create an instance of MyClass first.
test = MyClass()
print test.f()
print MyClass.i
You don't need to create an instance of MyClass for i, because it is a class member, not an instance member.
这篇关于Python类属性引用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!