如何确定 Python 中对象的大小? [英] How do I determine the size of an object in Python?

查看:33
本文介绍了如何确定 Python 中对象的大小?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道如何在 Python 中获取字符串、整数等对象的大小.

相关问题:有多少Python 列表(元组)中是否存在每个元素的字节数?

我正在使用一个 XML 文件,其中包含指定值大小的大小字段.我必须解析这个 XML 并进行编码.当我想更改特定字段的值时,我将检查该值的大小字段.这里我想比较一下我要输入的新值是否与XML中的大小相同.我需要检查新值的大小.如果是字符串,我可以说它的长度.但是对于 int、float 等,我很困惑.

解决方案

只需使用 sys 模块中定义的 >sys.getsizeof 函数.

<块引用>

sys.getsizeof(object[, default]):

以字节为单位返回对象的大小.对象可以是任何类型的对象.所有内置对象都会返回正确的结果,但这不必须适用于第三方扩展,因为它是实现具体.

只有直接归因于对象的内存消耗是占,而不是它所指对象的内存消耗.

default 参数允许定义一个将返回的值,如果对象类型不提供方法检索大小并会导致类型错误.

getsizeof 调用对象的__sizeof__ 方法并添加额外的垃圾收集器开销如果对象由垃圾收集器.

请参阅recursive sizeof recipe 以获取使用 getsizeof() 递归查找容器的大小及其所有内容.

用法示例,在python 3.0中:

<预><代码>>>>导入系统>>>x = 2>>>sys.getsizeof(x)24>>>sys.getsizeof(sys.getsizeof)32>>>sys.getsizeof('this')38>>>sys.getsizeof('这也是')48

如果你在 python <2.6 并且没有 sys.getsizeof 你可以使用 这个扩展模块 代替.不过没用过.

I want to know how to get size of objects like a string, integer, etc. in Python.

Related question: How many bytes per element are there in a Python list (tuple)?

I am using an XML file which contains size fields that specify the size of value. I must parse this XML and do my coding. When I want to change the value of a particular field, I will check the size field of that value. Here I want to compare whether the new value that I'm gong to enter is of the same size as in XML. I need to check the size of new value. In case of a string I can say its the length. But in case of int, float, etc. I am confused.

解决方案

Just use the sys.getsizeof function defined in the sys module.

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.

Only the memory consumption directly attributed to the object is accounted for, not the memory consumption of objects it refers to.

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.

See recursive sizeof recipe for an example of using getsizeof() recursively to find the size of containers and all their contents.

Usage example, in python 3.0:

>>> import sys
>>> x = 2
>>> sys.getsizeof(x)
24
>>> sys.getsizeof(sys.getsizeof)
32
>>> sys.getsizeof('this')
38
>>> sys.getsizeof('this also')
48

If you are in python < 2.6 and don't have sys.getsizeof you can use this extensive module instead. Never used it though.

这篇关于如何确定 Python 中对象的大小?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆