Object-oriented – Why isn’t there a static initializer in Python

decoratorobject-orientedpythonstatic methodsstatic-access

The equivalent of

static {
    // Code here
}

does not exist in Python by default. The closest thing, while being "Pythonic", seems to be to create a decorator and do the initialization there such as:

def static_initialization_decorator_for_myclass(cls):
    cls.initialize_static_stuff()
    return cls

@static_initialization_decorator_for_myclass
class MyClass:
    @classmethod
    def initialize_static_stuff():
        # Code here

Creating a new decorator for each class to do the same thing does not make sense. So, I thought of creating a standard decorator (say "initializestatic") and let that decorator call a given method name (say "init_static") like:

def initializestatic(cls):
    cls.init_static()
    return cls

@initializestatic
class MyClass:
    @classmethod
    def init_static():
        # Code here

This way, I can always use the same decorator and whenever I need a static initializer, I would put the following method in a class and would put @initializestatic decorator on top of the class:

@classmethod
def init_static():
    # Code here

Given it is that simple, why isn't there a built-in solution for static initialization in Python? I know that this sounds like a rant rather than a question but I am curious of the possible motives for excluding a static initializer from Python.

Best Answer

... why isn't there a built-in solution for static initialization in Python?

There is, you just put static initialization stuff in the class definition, i.e.

>>> class myclass:
...     print "anything in the class definition will be executed once!"
...     val = 42
...     def __init__(self,v):
...             self.v = v
...     def pr(self):
...             print self.v, self.val, myclass.val
...     def set(self,v):
...             self.val = v
...     def clsset(self, v):
...             myclass.val = v
...
anything in the class definition will be executed once!
>>> m = myclass(1)
>>> m.pr()
1 42 42
>>> m.set(2)
>>> m.clsset(24)
>>> m.pr()
1 2 24
>>> mm = myclass(2)
>>> mm.pr()
2 24 24
>>> mm.set(42)
>>> mm.pr()
2 42 24

Edit: I used print as an example of an arbitrary piece of code; here is another example:

>>> class myclass:
...     val = 42
...     dv = val * 1.2
...     def pr(self):
...             print self.dv
...
>>> m = myclass()
>>> m.pr()
50.4
Related Topic