为什么 Python 使用“魔法方法"? [英] Why does Python use 'magic methods'?

查看:51
本文介绍了为什么 Python 使用“魔法方法"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I've been playing around with Python recently, and one thing I'm finding a bit odd is the extensive use of 'magic methods', e.g. to make its length available, an object implements a method, def __len__(self), and then it is called when you write len(obj).

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

I was just wondering why objects don't simply define a len(self) method and have it called directly as a member of the object, e.g. obj.len()? I'm sure there must be good reasons for Python doing it the way it does, but as a newbie I haven't worked out what they are yet.

推荐答案

AFAIK, len 在这方面很特别,有历史渊源.

AFAIK, len is special in this respect and has historical roots.

这里引用来自常见问题解答:

为什么 Python 对某些方法使用方法功能(例如 list.index())但是其他函数(例如 len(list))?

主要原因是历史.职能用于那些操作对于一组类型是通用的,并且甚至是为了工作没有方法的对象所有(例如元组).也是方便有一个功能可以易于应用于无定形使用对象时的集合Python 的功能特性 (map(),apply() 等.

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).

其实就是实现len(), max(),min() 作为内置函数是实际上代码比实现少它们作为每种类型的方法.一罐对个别案件的狡辩,但它是 Python 的一部分,也是做出如此根本性的改变已晚现在.功能必须保持到避免大量代码损坏.

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 民间传说中实际上称为特殊方法)很有意义,并且在其他语言中也存在类似的功能.它们主要用于在使用特殊语法时隐式调用的代码.

The other "magical methods" (actually called special method in the Python folklore) make lots of sense, and similar functionality exists in other languages. They're mostly used for code that gets called implicitly when special syntax is used.

例如:

  • 重载运算符(存在于 C++ 和其他中)
  • 构造函数/析构函数
  • 用于访问属性的钩子
  • 元编程工具

等等...

这篇关于为什么 Python 使用“魔法方法"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆