函数变量stati的Python生成方法

2024-04-26 07:58:22 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我指的是一个在C++ +/p>中表现为静态变量的变量。


Tags: 方法定义静态staticmethod
1条回答
网友
1楼 · 发布于 2024-04-26 07:58:22

当然,您应该如您所指出的那样创建一个静态(或类)变量。你知道吗

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

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

相关问题 更多 >