Python class attribute referencing

2019-02-26 04:46发布

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.

标签: python class
2条回答
一夜七次
2楼-- · 2019-02-26 05:28

Always a function is called by its name, which is represented by (). So use MyClass.f()

查看更多
相关推荐>>
3楼-- · 2019-02-26 05:32

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.

查看更多
登录 后发表回答