Creating a static class with no instances

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

    The Pythonic way to create a static class is simply to declare those methods outside of a class (Java uses classes both for objects and for grouping related functions, but Python modules are sufficient for grouping related functions that do not require any object instance). However, if you insist on making a method at the class level that doesn't require an instance (rather than simply making it a free-standing function in your module), you can do so by using the "@staticmethod" decorator.

    That is, the Pythonic way would be:

    # My module
    elements = []
    
    def add_element(x):
      elements.append(x)
    

    But if you want to mirror the structure of Java, you can do:

    # My module
    class World(object):
      elements = []
    
      @staticmethod
      def add_element(x):
        World.elements.append(x)
    

    You can also do this with @classmethod if you care to know the specific class (which can be handy if you want to allow the static method to be inherited by a class inheriting from this class):

    # My module
    class World(object):
      elements = []
    
      @classmethod
      def add_element(cls, x):
        cls.elements.append(x)
    

提交回复
热议问题