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.

rbairos
  • 2,764
  • 2
  • 15
  • 12
  • see the answers of http://stackoverflow.com/questions/68645/static-class-variables-in-python – bilash.saha Nov 04 '11 at 21:49
  • http://docs.python.org/extending/extending.html – bilash.saha Nov 04 '11 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 – rbairos Nov 04 '11 at 22:10
  • make your question a bit clear.may be with a example about what you want... – bilash.saha Nov 04 '11 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). – rbairos Nov 04 '11 at 22:14

1 Answers1

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.

yak
  • 8,851
  • 2
  • 29
  • 23