如何确定Python中对象的大小? [英] How do I determine the size of an object in Python?
问题描述
我想知道如何在Python中获取对象的大小,例如字符串,整数等.
I want to know how to get size of objects like a string, integer, etc. in Python.
相关问题:有多少个每个元素的字节数是否在Python列表(元组)中?
我正在使用一个XML文件,其中包含指定值大小的大小字段.我必须解析此XML并进行编码.当我想更改特定字段的值时,我将检查该值的大小字段.在这里,我想比较输入的新值是否与XML中的值相同.我需要检查新值的大小.如果是字符串,我可以说它的长度.但是如果是int,float等,我会感到困惑.
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.
推荐答案
只需使用sys模块中定义的> sys.getsizeof 函数.
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.
default
参数允许定义
如果
对象类型不提供以下手段
检索大小,将导致
TypeError
.
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
调用对象的
__sizeof__
方法,并增加了额外的垃圾收集器开销
如果对象是由
垃圾收集器.
getsizeof
calls the object’s
__sizeof__
method and adds an additional garbage collector overhead
if the object is managed by the
garbage collector.
在python 3.0中的用法示例:
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
如果您使用的是python< 2.6且没有sys.getsizeof
,则可以使用此扩展模块.没用过.
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屋!