[python] Creating a static class with no instances

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.

How do I create a class (static in Java) so that I can access all methods and attributes of that class without having to create new instances/objects?

For example:

class World:

    allElems = []

    def addElem(x):  

        allElems.append(x)

World.addElem(6)
print(World.allElems)

EDIT

class World(object):

    allAirports = []

    @staticmethod
    def initialize():

        f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
        file_reader = csv.reader(f)

        for col in file_reader:

            allAirports.append(Airport(col[0],col[2],col[3]))

error: name 'allAirports' is not defined

This question is related to python class object static

The answer is


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)

Seems that you need classmethod:

class World(object):

    allAirports = []

    @classmethod
    def initialize(cls):

        if not cls.allAirports:
            f = open(os.path.expanduser("~/Desktop/1000airports.csv"))
            file_reader = csv.reader(f)

            for col in file_reader:
                cls.allAirports.append(Airport(col[0],col[2],col[3]))

        return cls.allAirports

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.


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()

Examples related to python

programming a servo thru a barometer Is there a way to view two blocks of code from the same file simultaneously in Sublime Text? python variable NameError Why my regexp for hyphenated words doesn't work? Comparing a variable with a string python not working when redirecting from bash script is it possible to add colors to python output? Get Public URL for File - Google Cloud Storage - App Engine (Python) Real time face detection OpenCV, Python xlrd.biffh.XLRDError: Excel xlsx file; not supported Could not load dynamic library 'cudart64_101.dll' on tensorflow CPU-only installation

Examples related to class

String method cannot be found in a main class method Class constructor type in typescript? ReactJS - Call One Component Method From Another Component How do I declare a model class in my Angular 2 component using TypeScript? When to use Interface and Model in TypeScript / Angular Swift Error: Editor placeholder in source file Declaring static constants in ES6 classes? Creating a static class with no instances In R, dealing with Error: ggplot2 doesn't know how to deal with data of class numeric Static vs class functions/variables in Swift classes?

Examples related to object

How to update an "array of objects" with Firestore? how to remove json object key and value.? Cast object to interface in TypeScript Angular 4 default radio button checked by default How to use Object.values with typescript? How to map an array of objects in React How to group an array of objects by key push object into array Add property to an array of objects access key and value of object using *ngFor

Examples related to static

What is the equivalent of Java static methods in Kotlin? Creating a static class with no instances Static vs class functions/variables in Swift classes? Call static methods from regular ES6 class methods What is the difference between static func and class func in Swift? An object reference is required to access a non-static member Mocking static methods with Mockito @Autowired and static method The static keyword and its various uses in C++ Non-Static method cannot be referenced from a static context with methods and variables