Python将函数变量设置为静态的方法

Dru*_*sky 2 python static-methods

我必须@staticmethod在类内部创建一个。我想知道是否有任何方法可以“保存”在两个顺序调用之间的静态方法内部定义的变量。

我的意思是一个行为类似于 C++ 中的静态变量的变量

Jon*_*IAR 5

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

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")
Run Code Online (Sandbox Code Playgroud)

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