为什么类方法不被调用?

and*_*lis -3 python methods class python-3.x

我试图调用类方法"func",它应该打印一些东西,但它永远不会被打印......没有错误,只是沉默.代码如下:

class AnyClass():
    atr1=0
    atr2='text'

    def func():
        print ('Ran Func')

a = AnyClass()
a.func
Run Code Online (Sandbox Code Playgroud)

Cor*_*mer 6

a.func只是方法对象的名称.你必须打电话给().

>>> a.func
<bound method AnyClass.func of <__main__.AnyClass object at 0x0000000003506240>>

>>> a.func()
Ran Func
Run Code Online (Sandbox Code Playgroud)

另请注意,self除非使用@staticmethod装饰器,否则必须在定义时将其作为第一个参数传递给方法.

def func(self):
        print ('Ran Func')
Run Code Online (Sandbox Code Playgroud)