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.
static { }
” in what language…?