Python 使函数变量成为静态变量的方法

Python way to make a function variable static

我必须在 class 中创建一个 @staticmethod。我想知道是否有任何方法可以 "save" 在两个顺序调用之间的静态方法中定义的变量。

我的意思是一个在 C++ 中表现得像静态变量的变量

当然,您应该按照您指出的那样创建一个静态(或class)变量。

class Example:
    name = "Example"  #  usually called a class-variable

    @staticmethod
    def static(newName=None):
        if newName is not None:
            Example.name = newName

        print ("%s static() called" % Example.name)



    @classmethod
    def cls_static(cls, newName=None):
        if newName is not None:
            cls.name = newName

        print ("%s static() called" % cls.name)

Example.static()
Example.static("john")

Example.cls_static()
Example.cls_static("bob")

根据您的喜好,您可以使用其中一个。我让您阅读此 link 以获取更多信息:http://radek.io/2011/07/21/static-variables-and-methods-in-python/