编程语言
首页 > 编程语言> > 为什么Python使用’魔术方法’?

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

作者:互联网

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

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

解决方法:

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

这是from the FAQ的报价:

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
来源: https://codeday.me/bug/20190923/1814662.html