Python函数(function)与方法(method)区别

KongYun    2018-01-22 21:49

在C++和Java中,好像函数即方法,方法即函数。后来学习Python,一直以为如此,实则非也。

如下代码:

def fun():
    pass
print (fun)

运行结果如下:

发现:

     单独定义的一个function是function,它是一个函数。换句话说,在class外部定义的可执行函数,都是函数。

再如下代码:

class Apple:

    def fun1(self):
        return 'normal'

    @staticmethod
    def fun2():

        return 'staticmethod'

    @classmethod
    def fun3(cls):

        return 'classmethod'


print (Apple.fun1)
print (Apple.fun2)
print (Apple.fun3)

print ("-"*80)

apple = Apple()
print (apple.fun1)
print (apple.fun2)
print (apple.fun3)

运行结果:

发现:

  • 在class内定义的普通方法,如fun1,因为它是要面向将来实例化对象的,其实它就是一个实例方法。它属于method,是一个方法。
  • 在class内定义的静态方法,如fun2,它与任何对象都没有联系,等同于是在class外定义的function,它属于函数。
  • 在class内定义的类方法,如fun3,它第一个参数必须是cls,它与class本身是绑定关系,它属于方法。

总结:

  1. 与类和实例无绑定关系的function都属于函数(function);
  2. 与类和实例有绑定关系的function都属于方法(method)。

  嗯,本人参考资料,就是这样理解的。

Views: 2.2K

[[total]] comments

Post your comment
  1. [[item.time]]
    [[item.user.username]] [[item.floor]]Floor
  2. Click to load more...
  3. Post your comment