Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>The documentation for these is at <a href="http://docs.python.org/3.0/c-api/typeobj.html" rel="noreferrer">http://docs.python.org/3.0/c-api/typeobj.html</a> and <a href="http://docs.python.org/3.0/extending/newtypes.html" rel="noreferrer">http://docs.python.org/3.0/extending/newtypes.html</a> describes how to make your own type.</p> <p>tp_alloc does the low-level memory allocation for the instance. This is equivalent to malloc(), plus initialize the refcnt to 1. Python has it's own allocator, PyType_GenericAlloc, but a type can implement a specialized allocator.</p> <p>tp_new is the same as Python's __new__. It's usually used for immutable objects where the data is stored in the instance itself, as compared to a pointer to data. For example, strings and tuples store their data in the instance, instead of using a char * or a PyTuple *.</p> <p>For this case, tp_new figures out how much memory is needed, based on the input parameters, and calls tp_alloc to get the memory, then initializes the essential fields. tp_new does not need to call tp_alloc. It can for example return a cached object.</p> <p>tp_init is the same as Python's __init__. Most of your initialization should be in this function.</p> <p>The distinction between __new__ and __init__ is called <a href="http://groups.google.com/group/comp.lang.python/msg/e78840758484b94d" rel="noreferrer">two-stage initialization</a>, or <a href="http://groups.google.com/group/comp.lang.python/browse_thread/thread/b129dc656f4d0c8b/e43ae56909c3c00a?lnk=gst&amp;q=two-phase+init#e43ae56909c3c00a" rel="noreferrer">two-phase initialization</a>. </p> <p>You say "<em>c++ just has new</em>" but that's not correct. tp_alloc corresponds a custom arena allocator in C++, __new__ corresponds to a custom type allocator (a factory function), and __init__ is more like the constructor. That last link discusses more about the parallels between C++ and Python style.</p> <p>Also read <a href="http://www.python.org/download/releases/2.2/descrintro/" rel="noreferrer">http://www.python.org/download/releases/2.2/descrintro/</a> for details about how __new__ and __init__ interact.</p> <p>You write that you want to "create the object directly in c++". That's rather difficult because at the least you'll have to convert any Python exceptions that occurred during object instantiation into a C++ exception. You might try looking at Boost::Python for some help with this task. Or you can use a two-phase initialization. ;)</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload