4

How would one go about specifying a static method or variable in a python class, in CPython C++?

In the PyTypeObject structure, tp_getset, tp_methods, tp_members all seem to assume an instance of the class.

Thanks very much, Rob.

5
  • see the answers of stackoverflow.com/questions/68645/… Commented Nov 4, 2011 at 21:49
  • docs.python.org/extending/extending.html Commented Nov 4, 2011 at 22:06
  • 1
    The first link does not refer to C++ while the second link does not refer to static variables in python classes. Is there something in those links Im missing that relates to my question? Thanks Commented Nov 4, 2011 at 22:10
  • make your question a bit clear.may be with a example about what you want... Commented Nov 4, 2011 at 22:12
  • In CPython, you can extend python with new types etc, by setting up a PyTypeObject structure. There does not seem to be any way to define static methods and variables in this structure, only regular methods and variables (tp_getset, tp_methods, tp_members, etc). Commented Nov 4, 2011 at 22:14

1 Answer 1

2

Static and class methods can be defined in tp_methods by adding METH_STATIC or METH_CLASS to the ml_flags field of the PyMethodDef structure. This is equivalent to @staticmethod and @classmethod decorators.

The first parameter of the method, which normally is the instance pointer, will be NULL for static methods and PyTypeObject* for class methods.

http://docs.python.org/c-api/structures.html#PyMethodDef

Class attributes can be added by setting the tp_dict to a dictionary with these attributes before calling PyType_Ready() (in your module initialization function). Alternatively tp_dict can be left as NULL in which case PyType_Ready() will create the dict for you. The attributes can then be added to that dict.

http://docs.python.org/c-api/typeobj.html#tp_dict

Computed class attributes require a descriptor class, exactly as in Python. An instance of the descriptor should then be added to the tp_dict as with other class attributes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.