为什么 Python 代码使用 len() 函数而不是长度方法? [英] Why does Python code use len() function instead of a length method?

查看:38
本文介绍了为什么 Python 代码使用 len() 函数而不是长度方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道python有一个len()函数用于确定字符串的大小,但我想知道为什么它不是字符串对象的方法.

I know that python has a len() function that is used to determine the size of a string, but I was wondering why it's not a method of the string object.

好吧,我意识到我错了.__len__() 实际上是一个字符串对象的方法.在字符串对象上使用 len 函数在 Python 中看到面向对象的代码似乎很奇怪.此外,看到 __len__ 作为名称而不仅仅是 len 也很奇怪.

Ok, I realized I was embarrassingly mistaken. __len__() is actually a method of a string object. It just seems weird to see object oriented code in Python using the len function on string objects. Furthermore, it's also weird to see __len__ as the name instead of just len.

推荐答案

字符串确实有长度方法:__len__()

Strings do have a length method: __len__()

Python 中的协议是在有长度的对象上实现这个方法并使用内置的 len() 函数,它为您调用它,类似于您实现 __iter__() 的方式 并在可迭代的对象上使用内置的 iter() 函数(或在幕后为您调用该方法).

The protocol in Python is to implement this method on objects which have a length and use the built-in len() function, which calls it for you, similar to the way you would implement __iter__() and use the built-in iter() function (or have the method called behind the scenes for you) on objects which are iterable.

有关详细信息,请参阅模拟容器类型.

See Emulating container types for more information.

这里有一篇关于 Python 协议主题的很好的读物:Python和最小惊讶原则

Here's a good read on the subject of protocols in Python: Python and the Principle of Least Astonishment

这篇关于为什么 Python 代码使用 len() 函数而不是长度方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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