user8953650
user8953650

Reputation: 1020

Python way to make a function variable static

I have to create a @staticmethod inside a class.. I would know if there is any way to "save" a variable defined inside the static method between two sequentially call.

I mean a variable that behave like static variable in C++

Upvotes: 2

Views: 143

Answers (1)

Jonathan DEKHTIAR
Jonathan DEKHTIAR

Reputation: 3536

Absolutely, you should create a static (or class) variable as you pointed out.

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

Depending on your preferences, you can use either one or the other. I let you read this link for more information: http://radek.io/2011/07/21/static-variables-and-methods-in-python/

Upvotes: 5

Related Questions