I want to do the equivalent of
class Foo(object):
bar = 1
using Python's C API. In other words, I want to create a Python class which has a static variable, using C.
How can I do this?
A way to keep the static variables in sync is to make them properties: class Test(object): , _i = 3 , @property , def i(self) , return type(self).
Python does not have a 'static' keyword to declare the static variable. In Python, you simply declare a variable inside the class, note that it should not be inside any method, and that variable will be known as a static or class variable.
We can define class members static using static keyword. When we declare a member of a class as static it means no matter how many objects of the class are created, there is only one copy of the static member. A static member is shared by all objects of the class.
Practical Data Science using Python When we declare a variable inside a class but outside any method, it is called as class or static variable in python. Class or static variable can be referred through a class but not directly through an instance.
Found it! It's just a matter of setting the tp_dict element of the type object and filling adding entries to it for each of the static variables. The following C code creates the same static variable as the Python code above:
PyTypeObject type;
// ...other initialisation...
type.tp_dict = PyDict_New();
PyDict_SetItemString(type.tp_dict, "bar", PyInt_FromLong(1));
You can pass that source code to Py_CompileString with the appropriate flags.
If you already have the class you could use PyObject_SetAttr.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With