Python中的静态方法?

新手上路,请多包涵

我可以定义一个可以直接在类实例上调用的 静态方法 吗?例如,

 MyClass.the_static_method()

原文由 Joan Venge 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 362
2 个回答

是的,使用 staticmethod 装饰器:

 class MyClass(object):
    @staticmethod
    def the_static_method(x):
        print(x)

MyClass.the_static_method(2)  # outputs 2

请注意,某些代码可能使用定义静态方法的旧方法,使用 staticmethod 作为函数而不是装饰器。仅当您必须支持 Python 的旧版本(2.2 和 2.3)时才应使用此选项:

 class MyClass(object):
    def the_static_method(x):
        print(x)
    the_static_method = staticmethod(the_static_method)

MyClass.the_static_method(2)  # outputs 2

这与第一个示例完全相同(使用 @staticmethod ),只是没有使用漂亮的装饰器语法。

最后,谨慎使用 staticmethod !在 Python 中很少有需要静态方法的情况,而且我已经看到它们多次使用,其中单独的“顶级”函数会更清晰。


以下是文档中的逐字记录

静态方法不接收隐式的第一个参数。要声明静态方法,请使用以下习惯用法:

 class C:
    @staticmethod
    def f(arg1, arg2, ...): ...

@staticmethod 形式是一个函数 装饰器——详见函数定义中 函数定义 的描述。

它可以在类(例如 C.f() )或实例(例如 C().f() )上调用。该实例被忽略,除了它的类。

Python 中的静态方法类似于 Java 或 C++ 中的静态方法。有关更高级的概念,请参阅 classmethod()

有关静态方法的更多信息,请参阅标准类型层次结构中 有关标准类型层次 结构的文档。

2.2 版中的新功能。

在 2.4 版更改: 添加了函数装饰器语法。

原文由 dbr 发布,翻译遵循 CC BY-SA 4.0 许可协议

我认为 史蒂文实际上是对的。要回答最初的问题,那么,为了设置类方法,只需假设第一个参数不会是调用实例,然后确保只从类中调用方法。

(请注意,此答案指的是 Python 3.x。在 Python 2.x 中,您将获得 TypeError 用于调用类本身的方法。)

例如:

 class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    def rollCall(n): #this is implicitly a class method (see comments below)
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)

在此代码中,“rollCall”方法假定第一个参数不是实例(如果它是由实例而不是类调用的话)。只要从类而不是实例调用“rollCall”,代码就可以正常工作。如果我们尝试从实例调用“rollCall”,例如:

 rex.rollCall(-1)

但是,它会引发异常,因为它会发送两个参数:它自己和 -1,而“rollCall”仅定义为接受一个参数。

顺便说一句,rex.rollCall() 会发送正确数量的参数,但也会引发异常,因为当函数期望 n 为数字时,现在 n 将代表 Dog 实例(即 rex)。

这就是装饰的用武之地:如果我们在“rollCall”方法之前加上

@staticmethod

然后,通过显式声明该方法是静态的,我们甚至可以从实例中调用它。现在,

 rex.rollCall(-1)

会工作。然后,在方法定义之前插入 @staticmethod 会阻止实例将自身作为参数发送。

您可以通过尝试以下代码来验证这一点,无论是否注释掉 @staticmethod 行。

 class Dog:
    count = 0 # this is a class variable
    dogs = [] # this is a class variable

    def __init__(self, name):
        self.name = name #self.name is an instance variable
        Dog.count += 1
        Dog.dogs.append(name)

    def bark(self, n): # this is an instance method
        print("{} says: {}".format(self.name, "woof! " * n))

    @staticmethod
    def rollCall(n):
        print("There are {} dogs.".format(Dog.count))
        if n >= len(Dog.dogs) or n < 0:
            print("They are:")
            for dog in Dog.dogs:
                print("  {}".format(dog))
        else:
            print("The dog indexed at {} is {}.".format(n, Dog.dogs[n]))

fido = Dog("Fido")
fido.bark(3)
Dog.rollCall(-1)
rex = Dog("Rex")
Dog.rollCall(0)
rex.rollCall(-1)

原文由 Richard Ambler 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题