Skip to content Skip to sidebar Skip to footer

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

Solution 1:

use type(self) for access to class attributes

>>> classA(object):
 var  = 2defwrite(self):
  printtype(self).var
>>> classB(A):
 pass>>> B().write()
2>>> B.var = 3>>> B().write()
3>>> A().write()
2

Solution 2:

You can access active through the class it belongs to:

if panelToggle.active:# do something

If you want to access the class variable from a method, you could write:

defam_i_active(self):
    """ This method will access the right *class* variable by
        looking at its own class type first.
    """if self.__class__.active:
        print'Yes, sir!'else:
        print'Nope.'

A working example can be found here: http://gist.github.com/522619


The self variable (named self by convention) is the current instance of the class, implicitly passed but explicitely recieved.

classA(object):

    answer = 42defadd(self, a, b):
        """ ``self`` is received explicitely. """return A.answer + a + b

a = A()

print a.add(1, 2) # ``The instance -- ``a`` -- is passed implicitely.``# => 45print a.answer 
# => print 42

Post a Comment for "Static Variable Inheritance In Python"