创建没有实例的静态类

我在网上看到的所有教程都展示了如何使用 __init__构造函数方法创建类,以便可以声明该类型的对象或该类的实例。

我如何创建一个类(Java 中的静态类) ,以便我可以访问那个类 没有的所有方法和属性,而这些方法和属性必须创建新的实例/对象?

例如:

class World:


allElems = []


def addElem(x):


allElems.append(x)


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

剪辑

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

没有定义 name‘ allAirports’

153369 次浏览

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

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)

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

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.

Ancient thread, but one way to make this work is:

class Static:
def __new__(cls):
raise TypeError('Static classes cannot be instantiated')

Then, you can use it like so:

class Foo(Static): ...

Seems the most 'Pythonic' to me, anyway.

Example use case: singleton class where I register handlers for conversion between types.

Cheers!