python 中巨大的类似列表的对象的长度
Length of giant list-like objects in python
我正在创建一个包含大量元素的类列表对象,但是当我 运行 下面的代码时,出现错误。
class test:
def __init__(self, n):
self.n = n
def __len__(self):
return self.n
instance = test(10**20)
print(len(instance))
我返回的错误是:
OverflowError:无法将 'int' 放入索引大小的整数
有人知道出了什么问题吗?
这是一个 CPython 实现细节。来自 __len__
docs:
In CPython, the length is required to be at most sys.maxsize
. If the
length is larger than sys.maxsize
some features (such as len()
)
may raise OverflowError
. To prevent raising OverflowError by truth
value testing, an object must define a __bool__()
method.
我正在创建一个包含大量元素的类列表对象,但是当我 运行 下面的代码时,出现错误。
class test:
def __init__(self, n):
self.n = n
def __len__(self):
return self.n
instance = test(10**20)
print(len(instance))
我返回的错误是: OverflowError:无法将 'int' 放入索引大小的整数
有人知道出了什么问题吗?
这是一个 CPython 实现细节。来自 __len__
docs:
In CPython, the length is required to be at most
sys.maxsize
. If the length is larger thansys.maxsize
some features (such aslen()
) may raiseOverflowError
. To prevent raising OverflowError by truth value testing, an object must define a__bool__()
method.