55

How can I declare a static attribute in Python?

Here is written how I can declare a method: Static methods in Python?

Community
  • 1
  • 1
Romulus
  • 1,150
  • 3
  • 16
  • 26
  • 2
    What are you calling "static" exactly ? The definition is very different from language to language. And even in the same language depending on where it's declared (like in C/C++, static at file level, static at function level or static at class level, 3 completely different thing...) – Cld Dec 15 '14 at 12:34
  • I have a class and I want all the objects to have by default a static attribute. In C++ you can write: `static int statischeVariable=5;` – Romulus Dec 15 '14 at 16:06

5 Answers5

98

All variables defined on the class level in Python are considered static

class Example:
    Variable = 2           # static variable

print Example.Variable     # prints 2   (static variable)

# Access through an instance
instance = Example()
print instance.Variable    # still 2  (ordinary variable)


# Change within an instance 
instance.Variable = 3      #(ordinary variable)
print instance.Variable    # 3   (ordinary variable)
print Example.Variable     # 2   (static variable)


# Change through Class 
Example.Variable = 5       #(static variable)
print instance.Variable    # 3  (ordinary variable)
print Example.Variable     # 5  (static variable)

You can have two different variables in your class under the same name (one static and one ordinary). Don't be confused.

Shahriar
  • 13,460
  • 8
  • 78
  • 95
  • 3
    this is a class variable, and has different behavior than e.g. `@staticmethod`. The only answer I see that correctly identifies the difference between class attributes and staticattributes is the downvoted one (!) – anon01 Oct 28 '20 at 02:20
21

Just to add to it, you can have static variables in functions as well, not only classes:

def some_fun():
    some_fun.i += 1
    print(some_fun.i)

some_fun.i = 0;
print(some_fun(), some_fun(), some_fun())  
# prints: 1,2,3  
Marcin
  • 215,873
  • 14
  • 235
  • 294
13

All variables declared inside the Class' body are 'static' attributes.

class SomeClass:
    # this is a class attribute
    some_attr = 1

    def __init__(self):
        # this is an instance attribute
        self.new_attr = 2

But keep in mind that the 'static' part is by convention, not imposed (for more details on this, read this SO thread).

For more details of this convention and its implications, here is a quick excerpt from the official documentation:

“Private” instance variables that cannot be accessed except from inside an object, don’t exist in Python. However, there is a convention that is followed by most Python code: a name prefixed with an underscore (e.g. _spam) should be treated as a non-public part of the API (whether it is a function, a method or a data member). It should be considered an implementation detail and subject to change without notice.

Since there is a valid use-case for class-private members (namely to avoid name clashes of names with names defined by subclasses), there is limited support for such a mechanism, called name mangling. Any identifier of the form __spam (at least two leading underscores, at most one trailing underscore) is textually replaced with _classname__spam, where classname is the current class name with leading underscore(s) stripped. This mangling is done without regard to the syntactic position of the identifier, as long as it occurs within the definition of a class.

Community
  • 1
  • 1
bosnjak
  • 8,424
  • 2
  • 21
  • 47
2

static attributes are data attributes in python. so that attributes assigned in class:-

>>>class A(object):
>>>    a = 1

>>>A.a
>>>1

This is different from C++ and Java, where a static member can't be accessed using an instance:-

>>>inst  = A()
>>>inst.a
1
>>> 

also builtin method setattr will help you to set static variable(data attribute).

>>>setattr(A, 'b', 2)
>>>A.b
>>>inst.b
Vishnu Upadhyay
  • 5,043
  • 1
  • 13
  • 24
  • 2
    The statement, "This is different from C++ and Java, where a static member can't be accessed using an instance" is completely incorrect. See https://ideone.com/ndh37g for an example. I think you may have accidentally switched the order in your statement, because the converse that "in C++ and Java, and instance member can't be accessed using a class" is true. – Travis Sep 15 '17 at 14:43
-6

You can use standard @property decorator to make static attribute:

class A(object):
    @property
    def a(self):
        return 1

a = A()
print a.a

1

a.a = 2

AttributeError: can't set attribute
Sergeev Andrew
  • 463
  • 4
  • 7