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

前端 未结 6 1024
日久生厌
日久生厌 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:33

    You can't call a classmethod in the class definition because the class hasn't been fully defined yet, so there's nothing to pass the method as its first cls argument...a classic chicken-and-egg problem. However you can work around this limitation by overloading the __new__() method in a metaclass, and calling the classmethod from there after the class has been created as illustrated below:

    class Test(object):
        # nested metaclass definition
        class __metaclass__(type):
            def __new__(mcl, classname, bases, classdict):
                cls = type.__new__(mcl, classname, bases, classdict)  # creates class
                cls.static_init()  # call the classmethod
                return cls
    
        x = None
    
        @classmethod
        def static_init(cls):  # called by metaclass when class is defined
            print("Hello")
            cls.x = 10
    
    print Test.x
    

    Output:

    Hello
    10
    

提交回复
热议问题