How would I add a static, typed member to a cython class? The syntax for adding typed instance-members uses the syntax as follows (e.g.):
import cython
cdef class NoStaticMembers:
cdef public int instanceValue # but, how do I create a static member??
def __init__(self, int value):
self.instanceValue = value
Yes, definitely possible to write static variables and methods in python. Static Variables : Variable declared at class level are called static variable which can be accessed directly using class name.
Note: To create a static member(block, variable, method, nested class), precede its declaration with the keyword static. When a member is declared static, it can be accessed before any objects of its class are created, and without reference to any object.
Static means, that the member is on a class level rather on the instance level. Static variables exist only on class level and aren't instantiated. If you change a static variable in one instance of the class, the change will affect its value in all other instances.
Just because you can do it in C really doesn't mean you can do it in Cython.
A workround might involve using global variables, and class properties so you can access them through class instances. I'm not sure if it's really better than using global variables though
import cython
cdef int MyClass_static_variable
cdef class MyClass:
property static_variable:
def __get__(self):
return MyClass_static_variable
def __set__(self, x):
global MyClass_static_variable
MyClass_static_variable = x
You'd have to measure how much speed you lost through that method (and maybe consider making __get__
and __set__
cpdef
if you can - I'm not sure). The only thing that doesn't let you do that a genuine static variable does is to access it as MyClass.static_variable
.
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