在编写大型脚本或包含许多行代码时,内存管理应该是我们的首要任务。因此,除了良好的编程知识外,我们还应该对如何高效处理内存有很好的了解。Python提供了许多函数来获取程序中特定对象的内存大小,其中之一是__sizeof__()函数。在本教程中,我们将学习__sizeof__()函数及其在Python程序中的工作方式。

Python的__sizeof__()函数

Python中的__sizeof__()函数并不精确地告诉我们对象的大小。它不返回生成器对象的大小,因为Python无法预先告诉我们生成器的大小。但实际上,它返回了占用内存的特定对象的内部大小(以字节为单位)。

为了理解这一点,让我们看一个具有无限生成器对象的示例程序。

示例1: 看下面的Python程序:

# A default function with endless generator object in it  
def endlessGenerator():  
    # A counting variable to initialize the generator  
    counting = 0  
    # Using while loop to create an endless generator  
    while True:  
             yield counting  
             counting += 1 # Creating infinite loop  
# Printing memory size of a generator object  
print("Internal memory size of endless generator object: ", endlessGenerator.__sizeof__())  

输出

Internal memory size of endless generator object:  120

解释:

我们使用了一个默认函数endlessGenerator()来创建程序中的无限生成器对象。在该函数中,我们初始化了一个变量counting = 0。我们在计数变量上使用了一个无限循环,没有在循环上设置断点。通过在函数中创建无限循环,我们使默认函数成为一个无限生成器对象。最后,我们使用__sizeof__()函数打印了无限生成器对象的内部内存大小。

现在,我们可以清楚地了解__sizeof__()函数的工作原理。由于上述程序中的无限生成器对象没有结束或断点,Python不能事先告诉我们生成器的大小。但同时,我们可以使用__sizeof__()函数检查生成器对象分配的内部内存,因为它必定会占用Python中的一些内部内存。

让我们看另一个示例,其中我们使用__sizeof__()函数获取内部内存大小而没有额外开销。

示例2:

# Define an empty list in the program  
emptyList = []  
# Printing size of empty list  
print("Internal memory size of an empty list: ", emptyList.__sizeof__())  
# Define some lists with elements  
a = [24]  
b = [24, 26, 31, 6]  
c = [1, 2, 6, 5, 415, 9, 23, 29]  
d = [4, 5, 12, 3, 2, 9, 20, 40, 32, 64]  
# Printing internal memory size of lists  
print("Memory size of first list: ", a.__sizeof__())  
print("Memory size of second list: ", b.__sizeof__())  
print("Memory size of third list: ", c.__sizeof__())  
print("Memory size of fourth list: ", d.__sizeof__()) 

输出

Internal memory size of an empty list:  40
Memory size of first list:  48
Memory size of second list:  104
Memory size of third list:  104
Memory size of fourth list:  136

解释:

使用__sizeof__()函数,我们可以清楚地看到空列表的内部内存大小为40字节,列表中的每个元素都会为列表的总内存大小增加8字节的大小。

标签: Tkinter教程, Tkinter安装, Tkinter库, Tkinter入门, Tkinter学习, Tkinter入门教程, Tkinter, Tkinter进阶, Tkinter指南, Tkinter学习指南, Tkinter进阶教程, Tkinter编程