簡體   English   中英

python 中巨型列表對象的長度

[英]Length of giant list-like objects in python

我正在創建一個類似列表的 object ,其中包含大量元素,但是當我運行以下代碼時,出現錯誤。

class test:
    def __init__(self, n):
        self.n = n
        
    def __len__(self):
        return self.n
    
instance = test(10**20)
print(len(instance))

我得到的錯誤是:OverflowError: cannot fit 'int' into an index-sized integer

有誰知道出了什么問題?

這是一個 CPython 實現細節。 __len__文檔

在 CPython 中,長度要求最多sys.maxsize 如果長度大於sys.maxsize某些功能(例如len() )可能會引發OverflowError 為了防止通過真值測試引發 OverflowError,object 必須定義一個__bool__()方法。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM