Python class attribute referencing

2019-02-26 05:18发布

问题:

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.

回答1:

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.



回答2:

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



标签: python class