问题
Short version
I recently came across some Python code in which the return type for a function was specified as PyObject
in the documentation. What is a PyObject
?
Detailed version
I am not a C/C++ programmer, but when I ran into PyObject
in the documentation linked above, Google taught me that PyObject
is a Python object as defined using the Python/C API. Specifically, the API documentation defines PyObject as follows:
All object types are extensions of this type. This is a type which contains the information Python needs to treat a pointer to an object as an object. In a normal “release” build, it contains only the object’s reference count and a pointer to the corresponding type object. It corresponds to the fields defined by the expansion of the PyObject_HEAD macro.
Frankly, I don't fully understand this, or whether it answers my basic question, but it doesn't make me think it is obviously wrong to just think of a PyObject
as a Python object, full stop. On the other hand, perhaps to technically count as a PyObject
the type must have been created as an extension to standard Python using the Python/C API. For instance, is an integer a PyObject
?
Potentially relevant links
http://docs.scipy.org/doc/numpy/reference/c-api.types-and-structures.html
回答1:
Every value you can touch in Python is a PyObject
in C. That includes lists, dictionaries, sockets, files, integers, strings, functions, classes, you name it. If you can touch it in Python, it’s a PyObject
in C.
回答2:
A PyObject
is in fact just a Python object at the C level. And since integers in Python are objects, they are also PyObject
s. It doesn't matter whether it was written in Python or in C, it is a PyObject
at the C level regardless.
来源:https://stackoverflow.com/questions/27683764/what-is-a-pyobject-in-python