Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/326.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/ms-access/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python len是怎么工作的?_Python - Fatal编程技术网

Python len是怎么工作的?

Python len是怎么工作的?,python,Python,len如何在Python上工作 看看这个例子: 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) 输出为: 42 <class '__main__.INT'> 42 <type 'int'&g

len如何在Python上工作

看看这个例子:

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)
输出为:

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

我认为你不能,除非你自己写。
内置len始终返回int。

您将无法返回。至少如果您希望它与python的其余部分一起工作。见

调用以实现内置的 函数len()。你应该归还 对象的长度,整数>=0。 另外,一个没有定义 非零()方法及其len()方法返回零在布尔值中被视为假 上下文


斜体强调我的意思。

不要这样做。你需要知道什么时候最好的答案是根本不去做你想做的事情。这是其中之一。

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

length = len(s)     # the reader assumes `q` is an int.
length.in_yards()   # the reader is going WTF?!
与其违背读者的期望,不如添加一种不同的方法:

s.length_in_yards()


p.S.并不能解决这个问题,但如果你有很好的理由编写自定义的整型对象,您可能会对允许此类对象直接用于索引内置序列的特殊方法感兴趣。

如果我重写len,可能会有任何问题?@Juanjo Conti:您会混淆其他阅读您的代码的开发人员,这会使您的代码更难重用。我不想这样做。你为什么认为这是个好主意?我同意ironfroggy的观点。你到底想完成什么?你的int子类和int有何不同?当然,例子中的int类只是一个例子。
s.length_in_yards()