python 魔法方法 为什么_为什么Python使用’魔术方法’?

我最近一直在玩Python,有一件事我发现有点奇怪的是广泛使用’魔术方法’,例如为了使其长度可用,一个对象实现了一个方法,def __len __(self),然后在你写len(obj)时调用它.

我只是想知道为什么对象不是简单地定义一个len(self)方法并且直接调用它作为对象的一个​​成员,例如obj.len()?我确信Python必须有充分的理由这样做,但作为一个新手,我还没有弄清楚它们到底是什么.

解决方法:

AFAIK,len在这方面是特殊的,具有历史根源.

Why does Python use methods for some

functionality (e.g. list.index()) but

functions for other (e.g. len(list))?

The major reason is history. Functions

were used for those operations that

were generic for a group of types and

which were intended to work even for

objects that didn’t have methods at

all (e.g. tuples). It is also

convenient to have a function that can

readily be applied to an amorphous

collection of objects when you use the

functional features of Python (map(),

apply() et al).

In fact, implementing len(), max(),

min() as a built-in function is

actually less code than implementing

them as methods for each type. One can

quibble about individual cases but

it’s a part of Python, and it’s too

late to make such fundamental changes

now. The functions have to remain to

avoid massive code breakage.

其他“神奇的方法”(实际上称为Python民间传说中的特殊方法)很有意义,其他语言也存在类似的功能.它们主要用于在使用特殊语法时隐式调用的代码.

例如:

>重载运算符(存在于C和其他)

>构造函数/析构函数

>用于访问属性的钩子

>元编程工具

等等…

标签:python,magic-methods

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值