1

I'm trying to declare static variable and now my code is:

class StaticClass:
    varA = 'hello'

    @staticmethod
    def staticMethod():
        varA='bye'

Result of code below is hello. Why not 'bye' ?

StaticClass.staticMethod()

print StaticClass.varA
5
  • 1
    That looks like a Java pattern, not like Python. What are you trying to achieve? Commented Feb 15, 2011 at 12:24
  • I'm trying to declare variable in one method , and have this variable accesable from other static methods in this class , and from other other class. Commented Feb 15, 2011 at 12:27
  • 3
    You don't need a method for that. This is Python, not Java. Commented Feb 15, 2011 at 12:38
  • @user278618: remember that this is Python, not Java, as @Daniel Roseman said. Maybe you've to re-design your classes before doing things like this. Have you considered using python properties? Commented Feb 15, 2011 at 13:49
  • "declare static variable" has no meaning in Python. Nothing is "declared". Why do you think you need this? Commented Feb 15, 2011 at 16:21

2 Answers 2

4

The code in staticMethod() assigns the string bye to the local variable varA, then returns, dropping the local variable. An assignment inside a function always creates local variables in Python. A staticmethod in Python has no means of accessing the class at all -- you need a classmethod for this purpose:

class StaticClass:
    var_a = 'hello'

    @classmethod
    def cls_method(cls):
        cls.var_a = 'bye'
Sign up to request clarification or add additional context in comments.

2 Comments

output of StaticClass.cls_method() print StaticClass.varA is 'hello'
@user278618: Are you sure? Notice that I renamed varA to var_a because CamelCase is only used for class names in Python.
1

It's because the varA you define in StaticClass.staticMethod() is in the method's namespace, not in the class namespace, if you want to access the class' varA you should do something like:

StaticClass.varA = 'bye'

By the way, you don't need to create a staticmethod to do this.

Comments

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.