Is there a static constructor or static initializer in Python?

后端 未结 6 754
星月不相逢
星月不相逢 2020-12-17 07:56

Is there such a thing as a static constructor in Python?

How do I implement a static constructor in Python?

Here is my code... The

6条回答
  •  心在旅途
    2020-12-17 08:27

    I create a static_init decorator which calls a static_init class method if it exists.

    Here is the decorator and example of how to use it to initialize a class variable on an enum class:

    # pylint: disable=missing-docstring,no-member
    
    import enum
    
    def static_init(cls):
        if getattr(cls, "static_init", None):
            cls.static_init()
        return cls
    
    @static_init
    class SomeEnum(enum.Enum):
        VAL_A = enum.auto()
        VAL_B = enum.auto()
        VAL_C = enum.auto()
        VAL_D = enum.auto()
    
        @classmethod
        def static_init(cls):
            text_dict = {}
            setattr(cls, 'text_dict', text_dict)
            for value in cls:
                text_dict[value.name.lower().replace("_", " ").title()] = value
    
    def test_static_init():
        assert SomeEnum.text_dict["Val A"] == SomeEnum.VAL_A
        assert SomeEnum.text_dict["Val B"] == SomeEnum.VAL_B
        assert SomeEnum.text_dict["Val C"] == SomeEnum.VAL_C
        assert SomeEnum.text_dict["Val D"] == SomeEnum.VAL_D
    

提交回复
热议问题