Python如何查看变量占用空间大小,python变量占用空间,在c语言中提供了size


在c语言中提供了sizeof可以用来查看一个变量占用的空间大小,在python中可以使用sys模块下的getsizeof方法来判断变量占用的空间大小。

其文档解释如下:

sys.getsizeof(object[, default]):

Return the size of an object in bytes. The object can be any type of object. All built-in objects will return correct results, but this does not have to hold true for third-party extensions as it is implementation specific.

The default argument allows to define a value which will be returned if the object type does not provide means to retrieve the size and would cause a TypeError.

getsizeof calls the object’s sizeof method and adds an additional garbage collector overhead if the object is managed by the garbage collector.

使用示例:

import sysv = 1print sys.getsizeof(v)s = 'abc'print sys.getsizeof(s)

评论关闭