python中 方法和函数的区别

一直以来都以为函数和方法是一个东西,平时区分也不是很详细,后来一搜索发现自己平时叫法是错的。

先看一段代码

def fun():
    pass
print fun
 
 
  • 1
  • 2
  • 3

结果如下:

<function fun at 0x00000000022BC3C8>
 
 
  • 1

可以看出:
单独定义的一个function是function,它是一个函数。我个人的理解是,在class外部定义的可执行函数,都是函数。

再看另外一段代码

#  coding:utf-8


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
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29

结果如下:

<unbound method Apple.fun1>
<function fun2 at 0x00000000021DC4A8>
<bound method classobj.fun3 of <class __main__.Apple at 0x0000000001D8C768>>
-------------------------------------------------------------------------------------
<bound method Apple.fun1 of <__main__.Apple instance at 0x00000000021DAE08>>
<function fun2 at 0x00000000021DC4A8>
<bound method classobj.fun3 of <class __main__.Apple at 0x0000000001D8C768>>
 
 
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7

可以看出:

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

简单总结:

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

谢谢,不对之处还请指正。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值