2

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++

1
  • This is a hint that you shouldn't be using a static method. Maybe a @classmethod instead, so you can store values on the class itself? Not that you can't assign directly -- MyClass._foo = bar -- but it's not a good smell. Commented Jul 12, 2018 at 11:20

1 Answer 1

5

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/

Sign up to request clarification or add additional context in comments.

2 Comments

In cls_static where does newName come from?
Oh sorry @GoswinvonBrederlow, I made a mistake, I edit my post

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.