Skip to main content
 首页 » 编程设计

python之了解 object.__flags__ 和 ndarray.__flags__

2024年09月07日13birdshome

object.__flags__ 的结果是什么意思?又该如何解读?

In [55]: str.__flags__ 
Out[55]: 269227008 
 
In [56]: list.__flags__ 
Out[56]: 34362368 
 
In [57]: tuple.__flags__ 
Out[57]: 67916800 
 
In [58]: object.__flags__ 
Out[58]: 791552 
 
In [59]: ndarray.__flags__ 
Out[59]: 791552 

此外,最重要的是,为什么我们对 object.__flags__ 和 ndarray.__flags__ 得到相同的结果?

请您参考如下方法:

使用链接的 SO:What does __flags__ in python type used for

和 object.h

很明显__flags__是 tpflags 的整数表示一个类的属性。显示为二进制,你的例子是:

In [165]: "{0:29b}".format(str.__flags__)     # high bit (1UL << 28) 
Out[165]: '10000000011000001010000000000' 
In [166]: "{0:29b}".format(tuple.__flags__)   # (1UL << 26) 
Out[166]: '  100000011000101010000000000' 
In [167]: "{0:29b}".format(list.__flags__)   # (1UL << 25) 
Out[167]: '   10000011000101010000000000' 

object没有这些高度特化的位:

In [168]: "{0:29b}".format(object.__flags__) 
Out[168]: '         11000001010000000000' 
In [169]: "{0:29b}".format(np.ndarray.__flags__) 
Out[169]: '         11000001010000000000' 
In [171]: "{0:29b}".format(1<<10 | 1<<12 | 1<<18 | 1<<19) 
Out[171]: '         11000001010000000000' 

np.ufunc没有 1<<10位,Py_TPFLAGS_BASETYPE .

In [170]: "{0:29b}".format(np.ufunc.__flags__) 
Out[170]: '         11000001000000000000' 

我不能继承它:

In [173]: class foo(np.ufunc): 
     ...:     pass 
TypeError: type 'numpy.ufunc' is not an acceptable base type 

用户定义类的标志是

In [176]: class Foo: 
     ...:     pass 
In [177]: "{0:29b}".format(Foo.__flags__) 
Out[177]: '         11000101011000000001' 

np.ndarray 的子类也是如此例如np.matrix .

我们可以搜索tpflags的numpy代码定义

https://github.com/numpy/numpy/search?utf8=%E2%9C%93&q=tpflags&type=

在arrayobject.c , 标志设置为 Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE .在 ufunc_object.c只是 Py_TPFLAGS_DEFAULT .

总之,__flags__表明 np.ndarray是一个普通的基类。 numpy不会尝试使用此属性设置任何特殊属性。