python 伦如何工作?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2171960/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 23:58:22  来源:igfitidea点击:

How does len work?

python

提问by Juanjo Conti

How does len work on Python?

len 如何在 Python 上工作?

Look at this example:

看这个例子:

class INT(int):
    pass

class STR(str):

    def __len__(self):
        return INT(42)

q = STR('how').__len__()
print q, type(q)
q = len(STR('how'))
print q, type(q)

The output is:

输出是:

42 <class '__main__.INT'>
42 <type 'int'>

How can I handle it so len returns an INT instance?

我该如何处理它以便 len 返回一个 INT 实例?

Answers suggest that the only solution is overriding len

答案表明唯一的解决方案是覆盖 len

This is my alternative implementation. It doesn't seem very harmful.

这是我的替代实现。看起来危害不大。

original_len = len
def len(o):
    l = o.__len__()
    if isinstance(l, int):
        return l
    original_len(o)

采纳答案by Pepijn

I don't think you can, unless you write your own len. The builtin len always return an int.

我认为你不能,除非你自己写 len。内置的 len 总是返回一个 int。

回答by ironfroggy

Do not do this. You need to learn when the best answer really is not to do what you are trying to do at all. This is one of those times.

不要这样做。你需要学习什么时候最好的答案真的不是做你想做的事。这是其中之一。

回答by Doug T.

You won't be able to. At least if you want it to work with the rest of python. See the definition of len

你将无法做到。至少如果您希望它与 Python 的其余部分一起使用。参见len定义

Called to implement the built-in function len(). Should return the length of the object, an integer >= 0. Also, an object that doesn't define a nonzero() method and whose len() method returns zero is considered to be false in a Boolean context.

调用以实现内置函数 len()。应该返回对象的长度,一个整数 >= 0。此外,未定义 非零() 方法且其len() 方法返回零的对象在布尔上下文中被认为是假的。

Italics emphasis mine.

斜体强调我的。

回答by Beni Cherniavsky-Paskin

As others say, don't do this. Consider how usage of this class would look:

正如其他人所说,不要这样做。考虑一下这个类的用法:

length = len(s)     # the reader assumes `q` is an int.
length.in_yards()   # the reader is going WTF?!

Instead of violating the reader's expectations, why don't you just add a different method:

与其违背读者的期望,不如添加一个不同的方法:

s.length_in_yards()


P.S. Doesn't solve this question, but if you have a good reason to write custom integer-like objects, you might be interested in the __index__special method that allows such object to be directly usable for indexing built-in sequences.

PS 不能解决这个问题,但是如果您有充分的理由编写自定义的类似整数的对象,您可能会对__index__允许此类对象直接用于索引内置序列的特殊方法感兴趣。