How can I access a classmethod from inside a class in Python

前端 未结 6 1018
日久生厌
日久生厌 2020-12-03 06:40

I would like to create a class in Python that manages above all static members. These members should be initiliazed during definition of the class already. Due to the fact t

6条回答
  •  情歌与酒
    2020-12-03 07:17

    After re-reading your question carefully this time I can think of two solutions. The first one is to apply the Borg design pattern. The second one is to discard the class method and use a module level function instead. This appears to solve your problem:

    def _test_static_init(value):
        return value, value * 2
    
    class Test:
        x, y = _test_static_init(20)
    
    if __name__ == "__main__":
        print Test.x, Test.y
    

    Old, incorrect answer:

    Here's an example, I hope it helps:

    class Test:
        x = None
    
        @classmethod
        def set_x_class(cls, value):
            Test.x = value
    
        def set_x_self(self):
            self.__class__.set_x_class(10)
    
    if __name__ == "__main__":
        obj = Test()
        print Test.x
        obj.set_x_self()
        print Test.x
        obj.__class__.set_x_class(15)
        print Test.x
    

    Anyway, NlightNFotis's answer is a better one: use the class name when accessing the class methods. It makes your code less obscure.

提交回复
热议问题