Creating a static class with no instances

后端 未结 4 1157
长发绾君心
长发绾君心 2021-02-02 05:22

All of the tutorials I see online show how to create classes with __init__ constructor methods so one can declare objects of that type, or instances of that class.<

4条回答
  •  天涯浪人
    2021-02-02 05:58

    You could use a classmethod or staticmethod

    class Paul(object):
        elems = []
    
        @classmethod
        def addelem(cls, e):
            cls.elems.append(e)
    
        @staticmethod
        def addelem2(e):
            Paul.elems.append(e)
    
    Paul.addelem(1)
    Paul.addelem2(2)
    
    print(Paul.elems)
    

    classmethod has advantage that it would work with sub classes, if you really wanted that functionality.

    module is certainly best though.

提交回复
热议问题