Python内置函数/内建函数,魔法方法、特殊方法 built-in functions、special method、magic method区别与联系

Python内置函数/内建函数,魔法方法、特殊方法 built-in functions、special method、magic method区别与联系

Python的内置函数与特殊方法、魔法方法概念既相关,又容易混淆,本文试图厘清其中关系。

内置函数/内建函数 built-in functions

内建函数(内建是相对于导入import来说的)是指python内部自带的函数,不需要导入外部包即可实现的函数,比如 len(),abs()等,Python针对众多的类型,提供了众多的内建函数来处理,这些内建函数功用在于其往往可对多种类型对象进行类似的操作,即多种类型对象的共有的操作;如果某种操作只对特殊的某一类对象可行,Python常将其设置为该种类型的方法(method)。

Python内置函数列表可参考:
https://docs.python.org/3.6/library/functions.html#import

特殊方法 special method

special method 就是一类有特殊名字 special names的方法,此特殊名字就是前后有双下划线,此类方法实质就是内建函数的底层函数,也即 len()函数调用的是__len()函数,abs()调用的是__abs(),特殊方法的列表
http://www.cnblogs.com/liao-sir/p/8416081.html

python 手册中关于特殊函数的部分:

3.3. Special method names
A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators. For instance, if a class defines a method named getitem(), and x is an instance of this class, then x[i] is roughly equivalent to type(x).getitem(x, i). Except where mentioned, attempts to execute an operation raise an exception when no appropriate method is defined (typically AttributeError or TypeError).、

全文链接:https://docs.python.org/3.6/reference/datamodel.html#specialnames

魔法函数

由于内置函数调用特殊函数是由解释器自动调用,比如 > 操作直接调用 gt() 特殊函数,看起来比较魔法,故也称特殊函数也为魔法函数。
特殊函数可以在类定义内重载,而且重载后相应的内置函数也会发生变化,但不能自己创造一个不存在的特殊函数名称。

由于特殊函数的可以重载,则可以给内置函数带来更多的功能和性质,可参考:

http://www.cnblogs.com/jhao/p/6022928.html

Special (magic) methods in Python

参考

1、python内置函数和魔法函数 https://www.cnblogs.com/ranjiewen/p/9219110.html

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值