Creating a static class with no instances

后端 未结 4 1207
长发绾君心
长发绾君心 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:38

    There are two ways to do that (Python 2.6+):

    static method

    class Klass(object):
        @staticmethod
        def static_method():
            print "Hello World"
    
    Klass.static_method()
    

    module

    your module file, called klass.py

    def static_method():
        print "Hello World"
    

    your code:

    import klass
    
    klass.static_method()
    

提交回复
热议问题