gpt4 book ai didi

python - Python 的内置类型是否有多余的特殊方法?

转载 作者:行者123 更新时间:2023-11-28 17:59:02 24 4
gpt4 key购买 nike

Fluent Python 他们说

You write len(my_object) and, if my_object is an instance of a user-defined class, then Python calls the __len__ instance method you implemented ...

But for built-in types like list, str, bytearray, and so on, the interpreter takes a shortcut: the CPython implementation of len() actually returns the value of the ob_size field in the PyVarObject C struct that represent the any variable-sized built-in object in memory.

但是 __len__ 仍然至少在其中一些上定义......

>>> 'string'.__len__()
6
>>> [1, 2, 3].__len__()
3

如果 len 不调用这些方法,它们有什么用?如果还有其他类似的例子,他们呢?

最佳答案

CPython 实现默认不调用 __len__() 的事实并不意味着没有任何 Python 库或用户程序会调用。保持方法可用与 API 稳定性有关,即使 CPython 尽可能走捷径也是如此。

关于python - Python 的内置类型是否有多余的特殊方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56613115/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com