Python class attribute referencing

前端 未结 2 960
时光说笑
时光说笑 2021-01-21 15:50

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 MyC         


        
相关标签:
2条回答
  • 2021-01-21 16:24

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

    0 讨论(0)
  • 2021-01-21 16:44

    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.

    0 讨论(0)
提交回复
热议问题