Python 创建一个没有实例的静态类

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30556857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 08:38:43  来源:igfitidea点击:

Creating a static class with no instances

pythonclassobjectstatic

提问by Greg Peckory

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.

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

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

如何创建一个类(Java 中的静态类),以便我可以访问该类的所有方法和属性,无需创建新的实例/对象?

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

错误:未定义名称“allAirports”

采纳答案by Michael Aaron Safyan

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.

创建静态类的 Pythonic 方法只是在类之外声明这些方法(Java 将类用于对象和对相关函数进行分组,但 Python 模块足以对不需要任何对象实例的相关函数进行分组)。但是,如果您坚持在类级别创建一个不需要实例的方法(而不是简单地使其成为模块中的独立函数),则可以使用“@staticmethod”装饰器来实现。

That is, the Pythonic way would be:

也就是说,Pythonic 的方式是:

# My module
elements = []

def add_element(x):
  elements.append(x)

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

但是如果你想镜像Java的结构,你可以这样做:

# My module
class World(object):
  elements = []

  @staticmethod
  def add_element(x):
    World.elements.append(x)

You can also do this with @classmethodif 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):

@classmethod如果您想知道特定的类,您也可以这样做(如果您希望允许从此类继承的类继承静态方法,这会很方便):

# My module
class World(object):
  elements = []

  @classmethod
  def add_element(cls, x):
    cls.elements.append(x)

回答by Eugene Soldatov

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

回答by boaz_shuster

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

有两种方法可以做到这一点(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

您的模块文件,称为 klass.py

def static_method():
    print "Hello World"

your code:

你的代码:

import klass

klass.static_method()

回答by Paul Rooney

You could use a classmethodor staticmethod

你可以使用一个classmethodstaticmethod

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

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

classmethod如果您真的想要该功能,它的优势在于它可以与子类一起使用。

module is certainly best though.

模块当然是最好的。