簡體   English   中英

使函數變量靜態化的Python方法

[英]Python way to make a function variable static

我必須在一個類中創建一個@staticmethod 。我想知道是否有任何方法可以“保存”兩個順序調用之間的static方法中定義的變量。

我的意思是一個行為類似於C ++中的靜態變量

絕對,您應該指出來創建一個靜態(或類)變量。

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/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM