len() 和 .__len__() 的区别? [英] Difference between len() and .__len__()?

查看:101
本文介绍了len() 和 .__len__() 的区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

调用 len([1,2,3])[1,2,3].__len__() 有什么区别吗?

Is there any difference between calling len([1,2,3]) or [1,2,3].__len__()?

如果没有明显的差异,那么幕后做了什么不同的事情?

If there is no visible difference, what is done differently behind the scenes?

推荐答案

len 是一个获取集合长度的函数.它通过调用对象的 __len__ 方法来工作.__something__ 属性是特殊的,通常比表面更重要,一般不应直接调用.

len is a function to get the length of a collection. It works by calling an object's __len__ method. __something__ attributes are special and usually more than meets the eye, and generally should not be called directly.

很久以前就决定获取某个东西的长度应该是一个函数而不是一个方法代码,理由是 len(a) 的含义对初学者来说很清楚,但是 a.len() 不会那么清楚.当 Python 开始时,__len__ 甚至不存在,len 是一个特殊的东西,它可以处理几种类型的对象.无论这给我们留下的情况是否完全合理,它都会留下来.

It was decided at some point long ago getting the length of something should be a function and not a method code, reasoning that len(a)'s meaning would be clear to beginners but a.len() would not be as clear. When Python started __len__ didn't even exist and len was a special thing that worked with a few types of objects. Whether or not the situation this leaves us makes total sense, it's here to stay.

这篇关于len() 和 .__len__() 的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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