Is there a static constructor or static initializer in Python?

后端 未结 6 753
星月不相逢
星月不相逢 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:10

    You can use the class method - see @classmethod decorator in the the code sample bellow:

    class A(object):
        _some_private_static_member = None
    
        @classmethod
        def reset_static_data_members(cls, some_value):
            cls._some_private_static_member = some_value
    
    A.reset_static_data_members("some static value")
    

    However, be aware, that this is most probably something you do NOT want to do, since it modifies state of type - so it will affect all further calls to methods of that type which use/depend-on the changed static class data members. Situation can get nasty if such static class data members are accessed & set via self. in instances of such class when you will easily get unexpected behaviour.

    Really correct way to do this (or the common sense way which most developers expect that behavior will be), is to make sure the static data members will be set only once - during import (the analogical way static data member initialisation behave in C++, C#, Java). Python has mechanism for that- the in-place initialisation:

    class A(object):
        _some_private_static_member_0 = "value 0"
        _some_private_static_member_1 = "value 1"
    

    Potentially you can initialise the static class members with return values from functions which abstract out (of the class) more complex value generation:

    class A(object):
        _some_private_static_member_0 = some_function_0()
        _some_private_static_member_1 = some_function_1()
    

提交回复
热议问题