Search code examples
pythoninheritancesyntaxstaticblender

Static variable inheritance in Python


I'm writing Python scripts for Blender for a project, but I'm pretty new to the language. Something I am confused about is the usage of static variables. Here is the piece of code I am currently working on:

class panelToggle(bpy.types.Operator):
    active = False

    def invoke(self, context, event):
        self.active = not self.active
        return{'FINISHED'}

class OBJECT_OT_openConstraintPanel(panelToggle):
    bl_label = "openConstraintPanel"
    bl_idname = "openConstraintPanel"

The idea is that the second class should inherit the active variable and the invoke method from the first, so that calling OBJECT_OT_openConstraintPanel.invoke() changes OBJECT_OT_openConstraintPanel.active. Using self as I did above won't work however, and neither does using panelToggle instead. Any idea of how I go about this?


Solution

  • use type(self) for access to class attributes

    >>> class A(object):
     var  = 2
     def write(self):
       print(type(self).var)
    >>> class B(A):
     pass
    >>> B().write()
    2
    >>> B.var = 3
    >>> B().write()
    3
    >>> A().write()
    2
    

    UPDATE

    for a classmethod is event easier, and most natural

    class A(object):
         var  = 2
         @classmethod
         def write(cls):
           print(cls.var)
    

    and a staticmethod should not depend on the instance type, so such form of dispatch is possible here