<p>How do I create class (i.e. <a href="https://en.wikipedia.org/wiki/Method_(computer_programming)#Static_methods" rel="nofollow noreferrer">static</a>) variables or methods in Python?</p>

[{'answer_id': 68672, 'author': 'Blair Conrad', 'author_id': 1199, 'author_profile': 'https://Stackoverflow.com/users/1199', 'pm_score': 12, 'selected': True, 'text': '<p>Variables declared inside the class definition, but not inside a method are class or static variables:</p>\n<pre><code>&gt;&gt;&gt; class MyClass:\n...     i = 3\n...\n&gt;&gt;&gt; MyClass.i\n3 \n</code></pre>\n<p>As @<a href="https://stackoverflow.com/questions/68645/static-class-variables-in-python#answer-69067">millerdev</a> points out, this creates a class-level <code>i</code> variable, but this is distinct from any instance-level <code>i</code> variable, so you could have</p>\n<pre><code>&gt;&gt;&gt; m = MyClass()\n&gt;&gt;&gt; m.i = 4\n&gt;&gt;&gt; MyClass.i, m.i\n&gt;&gt;&gt; (3, 4)\n</code></pre>\n<p>This is different from C++ and Java, but not so different from C#, where a static member can\'t be accessed using a reference to an instance.</p>\n<p>See <a href="https://docs.python.org/3/tutorial/classes.html#class-objects" rel="noreferrer">what the Python tutorial has to say on the subject of classes and class objects</a>.</p>\n<p>@Steve Johnson has already answered regarding <a href="http://web.archive.org/web/20090214211613/http://pyref.infogami.com/staticmethod" rel="noreferrer">static methods</a>, also documented under <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer">&quot;Built-in Functions&quot; in the Python Library Reference</a>.</p>\n<pre><code>class C:\n    @staticmethod\n    def f(arg1, arg2, ...): ...\n</code></pre>\n<p>@beidy recommends <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer">classmethod</a>s over staticmethod, as the method then receives the class type as the first argument.</p>\n'}, {'answer_id': 68747, 'author': 'emb', 'author_id': 10739, 'author_profile': 'https://Stackoverflow.com/users/10739', 'pm_score': 5, 'selected': False, 'text': "<p>Personally I would use a classmethod whenever I needed a static method. Mainly because I get the class as an argument.</p>\n\n<pre><code>class myObj(object):\n   def myMethod(cls)\n     ...\n   myMethod = classmethod(myMethod) \n</code></pre>\n\n<p>or use a decorator</p>\n\n<pre><code>class myObj(object):\n   @classmethod\n   def myMethod(cls)\n</code></pre>\n\n<p>For static properties.. Its time you look up some python definition.. variable can always change. There are two types of them mutable and immutable.. Also, there are class attributes and instance attributes.. Nothing really like static attributes in the sense of java &amp; c++</p>\n\n<p>Why use static method in pythonic sense, if it has no relation whatever to the class! If I were you, I'd either use classmethod or define the method independent from the class.</p>\n"}, {'answer_id': 68770, 'author': 'willurd', 'author_id': 1943957, 'author_profile': 'https://Stackoverflow.com/users/1943957', 'pm_score': 5, 'selected': False, 'text': '<p>Static methods in python are called <a href="http://pyref.infogami.com/classmethod" rel="noreferrer">classmethod</a>s. Take a look at the following code</p>\n\n<pre><code>class MyClass:\n\n    def myInstanceMethod(self):\n        print \'output from an instance method\'\n\n    @classmethod\n    def myStaticMethod(cls):\n        print \'output from a static method\'\n\n&gt;&gt;&gt; MyClass.myInstanceMethod()\nTraceback (most recent call last):\n  File "&lt;stdin&gt;", line 1, in &lt;module&gt;\nTypeError: unbound method myInstanceMethod() must be called [...]\n\n&gt;&gt;&gt; MyClass.myStaticMethod()\noutput from a static method\n</code></pre>\n\n<p>Notice that when we call the method <em>myInstanceMethod</em>, we get an error. This is because it requires that method be called on an instance of this class. The method <em>myStaticMethod</em> is set as a classmethod using the <a href="http://www.python.org/dev/peps/pep-0318/" rel="noreferrer">decorator</a> <em>@classmethod</em>.</p>\n\n<p>Just for kicks and giggles, we could call <em>myInstanceMethod</em> on the class by passing in an instance of the class, like so:</p>\n\n<pre><code>&gt;&gt;&gt; MyClass.myInstanceMethod(MyClass())\noutput from an instance method\n</code></pre>\n'}, {'answer_id': 69067, 'author': 'millerdev', 'author_id': 10840, 'author_profile': 'https://Stackoverflow.com/users/10840', 'pm_score': 10, 'selected': False, 'text': '<p>@Blair Conrad said static variables declared inside the class definition, but not inside a method are class or "static" variables:</p>\n\n<pre><code>&gt;&gt;&gt; class Test(object):\n...     i = 3\n...\n&gt;&gt;&gt; Test.i\n3\n</code></pre>\n\n<p>There are a few gotcha\'s here. Carrying on from the example above:</p>\n\n<pre><code>&gt;&gt;&gt; t = Test()\n&gt;&gt;&gt; t.i     # "static" variable accessed via instance\n3\n&gt;&gt;&gt; t.i = 5 # but if we assign to the instance ...\n&gt;&gt;&gt; Test.i  # we have not changed the "static" variable\n3\n&gt;&gt;&gt; t.i     # we have overwritten Test.i on t by creating a new attribute t.i\n5\n&gt;&gt;&gt; Test.i = 6 # to change the "static" variable we do it by assigning to the class\n&gt;&gt;&gt; t.i\n5\n&gt;&gt;&gt; Test.i\n6\n&gt;&gt;&gt; u = Test()\n&gt;&gt;&gt; u.i\n6           # changes to t do not affect new instances of Test\n\n# Namespaces are one honking great idea -- let\'s do more of those!\n&gt;&gt;&gt; Test.__dict__\n{\'i\': 6, ...}\n&gt;&gt;&gt; t.__dict__\n{\'i\': 5}\n&gt;&gt;&gt; u.__dict__\n{}\n</code></pre>\n\n<p>Notice how the instance variable <code>t.i</code> got out of sync with the "static" class variable when the attribute <code>i</code> was set directly on <code>t</code>. This is because <code>i</code> was re-bound within the <code>t</code> namespace, which is distinct from the <code>Test</code> namespace. If you want to change the value of a "static" variable, you must change it within the scope (or object) where it was originally defined. I put "static" in quotes because Python does not really have static variables in the sense that C++ and Java do.</p>\n\n<p>Although it doesn\'t say anything specific about static variables or methods, the <a href="http://docs.python.org/tut/" rel="noreferrer">Python tutorial</a> has some relevant information on <a href="https://docs.python.org/2/tutorial/classes.html" rel="noreferrer">classes and class objects</a>. </p>\n\n<p>@Steve Johnson also answered regarding static methods, also documented under "Built-in Functions" in the Python Library Reference.</p>\n\n<pre><code>class Test(object):\n    @staticmethod\n    def f(arg1, arg2, ...):\n        ...\n</code></pre>\n\n<p>@beid also mentioned classmethod, which is similar to staticmethod. A classmethod\'s first argument is the class object. Example:</p>\n\n<pre><code>class Test(object):\n    i = 3 # class (or static) variable\n    @classmethod\n    def g(cls, arg):\n        # here we can use \'cls\' instead of the class name (Test)\n        if arg &gt; cls.i:\n            cls.i = arg # would be the same as Test.i = arg1\n</code></pre>\n\n<p><a href="https://i.stack.imgur.com/xqnxe.jpg" rel="noreferrer"><img src="https://i.stack.imgur.com/xqnxe.jpg" alt="Pictorial Representation Of Above Example"></a></p>\n'}, {'answer_id': 79840, 'author': 'Ross', 'author_id': 14794, 'author_profile': 'https://Stackoverflow.com/users/14794', 'pm_score': 3, 'selected': False, 'text': "<p>To avoid any potential confusion, I would like to contrast static variables and immutable objects.</p>\n\n<p>Some primitive object types like integers, floats, strings, and touples are immutable in Python. This means that the object that is referred to by a given name cannot change if it is of one of the aforementioned object types. The name can be reassigned to a different object, but the object itself may not be changed.</p>\n\n<p>Making a variable static takes this a step further by disallowing the variable name to point to any object but that to which it currently points. (Note: this is a general software concept and not specific to Python; please see others' posts for information about implementing statics in Python).</p>\n"}, {'answer_id': 81002, 'author': 'Gregory', 'author_id': 14351, 'author_profile': 'https://Stackoverflow.com/users/14351', 'pm_score': 6, 'selected': False, 'text': '<p>You can also add class variables to classes on the fly</p>\n\n<pre><code>&gt;&gt;&gt; class X:\n...     pass\n... \n&gt;&gt;&gt; X.bar = 0\n&gt;&gt;&gt; x = X()\n&gt;&gt;&gt; x.bar\n0\n&gt;&gt;&gt; x.foo\nTraceback (most recent call last):\n  File "&lt;interactive input&gt;", line 1, in &lt;module&gt;\nAttributeError: X instance has no attribute \'foo\'\n&gt;&gt;&gt; X.foo = 1\n&gt;&gt;&gt; x.foo\n1\n</code></pre>\n\n<p>And class instances can change class variables</p>\n\n<pre><code>class X:\n  l = []\n  def __init__(self):\n    self.l.append(1)\n\nprint X().l\nprint X().l\n\n&gt;python test.py\n[1]\n[1, 1]\n</code></pre>\n'}, {'answer_id': 8201368, 'author': 'Bartosz Ptaszynski', 'author_id': 27098, 'author_profile': 'https://Stackoverflow.com/users/27098', 'pm_score': 4, 'selected': False, 'text': '<p>You could also enforce a class to be static using metaclass.</p>\n\n<pre><code>class StaticClassError(Exception):\n    pass\n\n\nclass StaticClass:\n    __metaclass__ = abc.ABCMeta\n\n    def __new__(cls, *args, **kw):\n        raise StaticClassError("%s is a static class and cannot be initiated."\n                                % cls)\n\nclass MyClass(StaticClass):\n    a = 1\n    b = 3\n\n    @staticmethod\n    def add(x, y):\n        return x+y\n</code></pre>\n\n<p>Then whenever by accident you try to initialize <strong>MyClass</strong> you\'ll get an StaticClassError.</p>\n'}, {'answer_id': 9613563, 'author': 'jondinham', 'author_id': 905418, 'author_profile': 'https://Stackoverflow.com/users/905418', 'pm_score': 5, 'selected': False, 'text': "<p>One special thing to note about static properties &amp; instance properties, shown in the example below:</p>\n\n<pre><code>class my_cls:\n  my_prop = 0\n\n#static property\nprint my_cls.my_prop  #--&gt; 0\n\n#assign value to static property\nmy_cls.my_prop = 1 \nprint my_cls.my_prop  #--&gt; 1\n\n#access static property thru' instance\nmy_inst = my_cls()\nprint my_inst.my_prop #--&gt; 1\n\n#instance property is different from static property \n#after being assigned a value\nmy_inst.my_prop = 2\nprint my_cls.my_prop  #--&gt; 1\nprint my_inst.my_prop #--&gt; 2\n</code></pre>\n\n<p>This means before assigning the value to instance property, if we try to access the property thru' instance, the static value is used. <strong>Each property declared in python class always has a static slot in memory</strong>.</p>\n"}, {'answer_id': 15117875, 'author': 'Tomer Zait', 'author_id': 1261677, 'author_profile': 'https://Stackoverflow.com/users/1261677', 'pm_score': 3, 'selected': False, 'text': '<p>The best way I found is to use another class. You can create an object and then use it on other objects.</p>\n\n<pre><code>class staticFlag:\n    def __init__(self):\n        self.__success = False\n    def isSuccess(self):\n        return self.__success\n    def succeed(self):\n        self.__success = True\n\nclass tryIt:\n    def __init__(self, staticFlag):\n        self.isSuccess = staticFlag.isSuccess\n        self.succeed = staticFlag.succeed\n\ntryArr = []\nflag = staticFlag()\nfor i in range(10):\n    tryArr.append(tryIt(flag))\n    if i == 5:\n        tryArr[i].succeed()\n    print tryArr[i].isSuccess()\n</code></pre>\n\n<p>With the example above, I made a class named <code>staticFlag</code>.</p>\n\n<p>This class should present the static var <code>__success</code> (Private Static Var).</p>\n\n<p><code>tryIt</code> class represented the regular class we need to use.</p>\n\n<p>Now I made an object for one flag (<code>staticFlag</code>). This flag will be sent as reference to all the regular objects.</p>\n\n<p>All these objects are being added to the list <code>tryArr</code>.</p>\n\n<hr>\n\n<p>This Script Results:</p>\n\n<pre><code>False\nFalse\nFalse\nFalse\nFalse\nTrue\nTrue\nTrue\nTrue\nTrue\n</code></pre>\n'}, {'answer_id': 15644143, 'author': 'user2209576', 'author_id': 2209576, 'author_profile': 'https://Stackoverflow.com/users/2209576', 'pm_score': 4, 'selected': False, 'text': '<p>When define some member variable outside any member method, the variable can be either static or non-static depending on how the variable is expressed. </p>\n\n<ul>\n<li>CLASSNAME.var is static variable</li>\n<li>INSTANCENAME.var is not static variable. </li>\n<li>self.var inside class is not static variable. </li>\n<li>var inside the class member function is not defined.</li>\n</ul>\n\n<p>For example:</p>\n\n<pre><code>#!/usr/bin/python\n\nclass A:\n    var=1\n\n    def printvar(self):\n        print "self.var is %d" % self.var\n        print "A.var is %d" % A.var\n\n\n    a = A()\n    a.var = 2\n    a.printvar()\n\n    A.var = 3\n    a.printvar()\n</code></pre>\n\n<p>The results are</p>\n\n<pre><code>self.var is 2\nA.var is 1\nself.var is 2\nA.var is 3\n</code></pre>\n'}, {'answer_id': 24553443, 'author': 'Yann', 'author_id': 717357, 'author_profile': 'https://Stackoverflow.com/users/717357', 'pm_score': 3, 'selected': False, 'text': '<p>In regards to this <a href="https://stackoverflow.com/a/68672/717357">answer</a>, for a <em>constant</em> static variable, you can use a descriptor. Here\'s an example:</p>\n\n<pre><code>class ConstantAttribute(object):\n    \'\'\'You can initialize my value but not change it.\'\'\'\n    def __init__(self, value):\n        self.value = value\n\n    def __get__(self, obj, type=None):\n        return self.value\n\n    def __set__(self, obj, val):\n        pass\n\n\nclass Demo(object):\n    x = ConstantAttribute(10)\n\n\nclass SubDemo(Demo):\n    x = 10\n\n\ndemo = Demo()\nsubdemo = SubDemo()\n# should not change\ndemo.x = 100\n# should change\nsubdemo.x = 100\nprint "small demo", demo.x\nprint "small subdemo", subdemo.x\nprint "big demo", Demo.x\nprint "big subdemo", SubDemo.x\n</code></pre>\n\n<p>resulting in ...</p>\n\n<pre><code>small demo 10\nsmall subdemo 100\nbig demo 10\nbig subdemo 10\n</code></pre>\n\n<p>You can always raise an exception if quietly ignoring setting value (<code>pass</code> above) is not your thing. If you\'re looking for a C++, Java style static class variable:</p>\n\n<pre><code>class StaticAttribute(object):\n    def __init__(self, value):\n        self.value = value\n\n    def __get__(self, obj, type=None):\n        return self.value\n\n    def __set__(self, obj, val):\n        self.value = val\n</code></pre>\n\n<p>Have a look at <a href="https://stackoverflow.com/a/102062/717357">this answer</a> and the official docs <a href="https://docs.python.org/2/howto/descriptor.html" rel="noreferrer">HOWTO</a> for more information about descriptors. </p>\n'}, {'answer_id': 27568860, 'author': 'Rick', 'author_id': 2437514, 'author_profile': 'https://Stackoverflow.com/users/2437514', 'pm_score': 8, 'selected': False, 'text': '<h2>Static and Class Methods</h2>\n<p>As the other answers have noted, static and class methods are easily accomplished using the built-in decorators:</p>\n<pre><code>class Test(object):\n\n    # regular instance method:\n    def my_method(self):\n        pass\n\n    # class method:\n    @classmethod\n    def my_class_method(cls):\n        pass\n\n    # static method:\n    @staticmethod\n    def my_static_method():\n        pass\n</code></pre>\n<p>As usual, the first argument to <code>my_method()</code> is bound to the class instance object. In contrast, the first argument to <code>my_class_method()</code> is <em>bound to the class object itself</em> (e.g., in this case, <code>Test</code>). For <code>my_static_method()</code>, none of the arguments are bound, and having arguments at all is optional.</p>\n<h2>&quot;Static Variables&quot;</h2>\n<p>However, implementing &quot;static variables&quot; (well, <em>mutable</em> static variables, anyway, if that\'s not a contradiction in terms...) is not as straight forward. As millerdev <a href="https://stackoverflow.com/a/69067/2437514">pointed out in his answer</a>, the problem is that Python\'s class attributes are not truly &quot;static variables&quot;. Consider:</p>\n<pre><code>class Test(object):\n    i = 3  # This is a class attribute\n\nx = Test()\nx.i = 12   # Attempt to change the value of the class attribute using x instance\nassert x.i == Test.i  # ERROR\nassert Test.i == 3    # Test.i was not affected\nassert x.i == 12      # x.i is a different object than Test.i\n</code></pre>\n<p>This is because the line <code>x.i = 12</code> has added a new instance attribute <code>i</code> to <code>x</code> instead of changing the value of the <code>Test</code> class <code>i</code> attribute.</p>\n<p><em>Partial</em> expected static variable behavior, i.e., syncing of the attribute between multiple instances (but <strong>not</strong> with the class itself; see &quot;gotcha&quot; below), can be achieved by turning the class attribute into a property:</p>\n<pre><code>class Test(object):\n\n    _i = 3\n\n    @property\n    def i(self):\n        return type(self)._i\n\n    @i.setter\n    def i(self,val):\n        type(self)._i = val\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting and setting i) ##\n\nclass Test(object):\n\n    _i = 3\n\n    def get_i(self):\n        return type(self)._i\n\n    def set_i(self,val):\n        type(self)._i = val\n\n    i = property(get_i, set_i)\n</code></pre>\n<p>Now you can do:</p>\n<pre><code>x1 = Test()\nx2 = Test()\nx1.i = 50\nassert x2.i == x1.i  # no error\nassert x2.i == 50    # the property is synced\n</code></pre>\n<p>The static variable will now remain in sync <em>between all class instances</em>.</p>\n<p>(NOTE: That is, unless a class instance decides to define its own version of <code>_i</code>! But if someone decides to do THAT, they deserve what they get, don\'t they???)</p>\n<p>Note that technically speaking, <code>i</code> is still not a \'static variable\' at all; it is a <code>property</code>, which is a special type of descriptor. However, the <code>property</code> behavior is now equivalent to a (mutable) static variable synced across all class instances.</p>\n<h2>Immutable &quot;Static Variables&quot;</h2>\n<p>For immutable static variable behavior, simply omit the <code>property</code> setter:</p>\n<pre><code>class Test(object):\n\n    _i = 3\n\n    @property\n    def i(self):\n        return type(self)._i\n\n## ALTERNATIVE IMPLEMENTATION - FUNCTIONALLY EQUIVALENT TO ABOVE ##\n## (except with separate methods for getting i) ##\n\nclass Test(object):\n\n    _i = 3\n\n    def get_i(self):\n        return type(self)._i\n\n    i = property(get_i)\n</code></pre>\n<p>Now attempting to set the instance <code>i</code> attribute will return an <code>AttributeError</code>:</p>\n<pre><code>x = Test()\nassert x.i == 3  # success\nx.i = 12         # ERROR\n</code></pre>\n<h2>One Gotcha to be Aware of</h2>\n<p>Note that the above methods only work with <em>instances</em> of your class - they will <strong>not</strong> work <em>when using the class itself</em>. So for example:</p>\n<pre><code>x = Test()\nassert x.i == Test.i  # ERROR\n\n# x.i and Test.i are two different objects:\ntype(Test.i)  # class \'property\'\ntype(x.i)     # class \'int\'\n</code></pre>\n<p>The line <code>assert Test.i == x.i</code> produces an error, because the <code>i</code> attribute of <code>Test</code> and <code>x</code> are two different objects.</p>\n<p>Many people will find this surprising. However, it should not be. If we go back and inspect our <code>Test</code> class definition (the second version), we take note of this line:</p>\n<pre><code>    i = property(get_i) \n</code></pre>\n<p>Clearly, the member <code>i</code> of <code>Test</code> must be a <code>property</code> object, which is the type of object returned from the <code>property</code> function.</p>\n<p>If you find the above confusing, you are most likely still thinking about it from the perspective of other languages (e.g. Java or c++). You should go study the <code>property</code> object, about the order in which Python attributes are returned, the descriptor protocol, and the method resolution order (MRO).</p>\n<p>I present a solution to the above \'gotcha\' below; however I would suggest - strenuously - that you do not try to do something like the following until - at minimum - you thoroughly understand why <code>assert Test.i = x.i</code> causes an error.</p>\n<h2><em>REAL, ACTUAL</em> Static Variables - <code>Test.i == x.i</code></h2>\n<p>I present the (Python 3) solution below for informational purposes only. I am not endorsing it as a &quot;good solution&quot;. I have my doubts as to whether emulating the static variable behavior of other languages in Python is ever actually necessary. However, regardless as to whether it is actually useful, the below should help further understanding of how Python works.</p>\n<p>UPDATE: this attempt <strong>is really pretty awful</strong>; if you insist on doing something like this (hint: please don\'t; Python is a very elegant language and shoe-horning it into behaving like another language is just not necessary), use the code in <a href="https://stackoverflow.com/a/36216964/2437514">Ethan Furman\'s answer</a> instead.</p>\n<p><strong>Emulating static variable behavior of other languages using a metaclass</strong></p>\n<p>A metaclass is the class of a class. The default metaclass for all classes in Python (i.e., the &quot;new style&quot; classes post Python 2.3 I believe) is <code>type</code>. For example:</p>\n<pre><code>type(int)  # class \'type\'\ntype(str)  # class \'type\'\nclass Test(): pass\ntype(Test) # class \'type\'\n</code></pre>\n<p>However, you can define your own metaclass like this:</p>\n<pre><code>class MyMeta(type): pass\n</code></pre>\n<p>And apply it to your own class like this (Python 3 only):</p>\n<pre><code>class MyClass(metaclass = MyMeta):\n    pass\n\ntype(MyClass)  # class MyMeta\n</code></pre>\n<p>Below is a metaclass I have created which attempts to emulate &quot;static variable&quot; behavior of other languages. It basically works by replacing the default getter, setter, and deleter with versions which check to see if the attribute being requested is a &quot;static variable&quot;.</p>\n<p>A catalog of the &quot;static variables&quot; is stored in the <code>StaticVarMeta.statics</code> attribute. All attribute requests are initially attempted to be resolved using a substitute resolution order. I have dubbed this the &quot;static resolution order&quot;, or &quot;SRO&quot;. This is done by looking for the requested attribute in the set of &quot;static variables&quot; for a given class (or its parent classes). If the attribute does not appear in the &quot;SRO&quot;, the class will fall back on the default attribute get/set/delete behavior (i.e., &quot;MRO&quot;).</p>\n<pre><code>from functools import wraps\n\nclass StaticVarsMeta(type):\n    \'\'\'A metaclass for creating classes that emulate the &quot;static variable&quot; behavior\n    of other languages. I do not advise actually using this for anything!!!\n    \n    Behavior is intended to be similar to classes that use __slots__. However, &quot;normal&quot;\n    attributes and __statics___ can coexist (unlike with __slots__). \n    \n    Example usage: \n        \n        class MyBaseClass(metaclass = StaticVarsMeta):\n            __statics__ = {\'a\',\'b\',\'c\'}\n            i = 0  # regular attribute\n            a = 1  # static var defined (optional)\n            \n        class MyParentClass(MyBaseClass):\n            __statics__ = {\'d\',\'e\',\'f\'}\n            j = 2              # regular attribute\n            d, e, f = 3, 4, 5  # Static vars\n            a, b, c = 6, 7, 8  # Static vars (inherited from MyBaseClass, defined/re-defined here)\n            \n        class MyChildClass(MyParentClass):\n            __statics__ = {\'a\',\'b\',\'c\'}\n            j = 2  # regular attribute (redefines j from MyParentClass)\n            d, e, f = 9, 10, 11   # Static vars (inherited from MyParentClass, redefined here)\n            a, b, c = 12, 13, 14  # Static vars (overriding previous definition in MyParentClass here)\'\'\'\n    statics = {}\n    def __new__(mcls, name, bases, namespace):\n        # Get the class object\n        cls = super().__new__(mcls, name, bases, namespace)\n        # Establish the &quot;statics resolution order&quot;\n        cls.__sro__ = tuple(c for c in cls.__mro__ if isinstance(c,mcls))\n                        \n        # Replace class getter, setter, and deleter for instance attributes\n        cls.__getattribute__ = StaticVarsMeta.__inst_getattribute__(cls, cls.__getattribute__)\n        cls.__setattr__ = StaticVarsMeta.__inst_setattr__(cls, cls.__setattr__)\n        cls.__delattr__ = StaticVarsMeta.__inst_delattr__(cls, cls.__delattr__)\n        # Store the list of static variables for the class object\n        # This list is permanent and cannot be changed, similar to __slots__\n        try:\n            mcls.statics[cls] = getattr(cls,\'__statics__\')\n        except AttributeError:\n            mcls.statics[cls] = namespace[\'__statics__\'] = set() # No static vars provided\n        # Check and make sure the statics var names are strings\n        if any(not isinstance(static,str) for static in mcls.statics[cls]):\n            typ = dict(zip((not isinstance(static,str) for static in mcls.statics[cls]), map(type,mcls.statics[cls])))[True].__name__\n            raise TypeError(\'__statics__ items must be strings, not {0}\'.format(typ))\n        # Move any previously existing, not overridden statics to the static var parent class(es)\n        if len(cls.__sro__) &gt; 1:\n            for attr,value in namespace.items():\n                if attr not in StaticVarsMeta.statics[cls] and attr != [\'__statics__\']:\n                    for c in cls.__sro__[1:]:\n                        if attr in StaticVarsMeta.statics[c]:\n                            setattr(c,attr,value)\n                            delattr(cls,attr)\n        return cls\n    def __inst_getattribute__(self, orig_getattribute):\n        \'\'\'Replaces the class __getattribute__\'\'\'\n        @wraps(orig_getattribute)\n        def wrapper(self, attr):\n            if StaticVarsMeta.is_static(type(self),attr):\n                return StaticVarsMeta.__getstatic__(type(self),attr)\n            else:\n                return orig_getattribute(self, attr)\n        return wrapper\n    def __inst_setattr__(self, orig_setattribute):\n        \'\'\'Replaces the class __setattr__\'\'\'\n        @wraps(orig_setattribute)\n        def wrapper(self, attr, value):\n            if StaticVarsMeta.is_static(type(self),attr):\n                StaticVarsMeta.__setstatic__(type(self),attr, value)\n            else:\n                orig_setattribute(self, attr, value)\n        return wrapper\n    def __inst_delattr__(self, orig_delattribute):\n        \'\'\'Replaces the class __delattr__\'\'\'\n        @wraps(orig_delattribute)\n        def wrapper(self, attr):\n            if StaticVarsMeta.is_static(type(self),attr):\n                StaticVarsMeta.__delstatic__(type(self),attr)\n            else:\n                orig_delattribute(self, attr)\n        return wrapper\n    def __getstatic__(cls,attr):\n        \'\'\'Static variable getter\'\'\'\n        for c in cls.__sro__:\n            if attr in StaticVarsMeta.statics[c]:\n                try:\n                    return getattr(c,attr)\n                except AttributeError:\n                    pass\n        raise AttributeError(cls.__name__ + &quot; object has no attribute \'{0}\'&quot;.format(attr))\n    def __setstatic__(cls,attr,value):\n        \'\'\'Static variable setter\'\'\'\n        for c in cls.__sro__:\n            if attr in StaticVarsMeta.statics[c]:\n                setattr(c,attr,value)\n                break\n    def __delstatic__(cls,attr):\n        \'\'\'Static variable deleter\'\'\'\n        for c in cls.__sro__:\n            if attr in StaticVarsMeta.statics[c]:\n                try:\n                    delattr(c,attr)\n                    break\n                except AttributeError:\n                    pass\n        raise AttributeError(cls.__name__ + &quot; object has no attribute \'{0}\'&quot;.format(attr))\n    def __delattr__(cls,attr):\n        \'\'\'Prevent __sro__ attribute from deletion\'\'\'\n        if attr == \'__sro__\':\n            raise AttributeError(\'readonly attribute\')\n        super().__delattr__(attr)\n    def is_static(cls,attr):\n        \'\'\'Returns True if an attribute is a static variable of any class in the __sro__\'\'\'\n        if any(attr in StaticVarsMeta.statics[c] for c in cls.__sro__):\n            return True\n        return False\n</code></pre>\n'}, {'answer_id': 36216964, 'author': 'Ethan Furman', 'author_id': 208880, 'author_profile': 'https://Stackoverflow.com/users/208880', 'pm_score': 4, 'selected': False, 'text': '<p>It is possible to have <code>static</code> class variables, but probably not worth the effort.</p>\n\n<p>Here\'s a proof-of-concept written in Python 3 -- if any of the exact details are wrong the code can be tweaked to match just about whatever you mean by a <code>static variable</code>:</p>\n\n<hr>\n\n<pre><code>class Static:\n    def __init__(self, value, doc=None):\n        self.deleted = False\n        self.value = value\n        self.__doc__ = doc\n    def __get__(self, inst, cls=None):\n        if self.deleted:\n            raise AttributeError(\'Attribute not set\')\n        return self.value\n    def __set__(self, inst, value):\n        self.deleted = False\n        self.value = value\n    def __delete__(self, inst):\n        self.deleted = True\n\nclass StaticType(type):\n    def __delattr__(cls, name):\n        obj = cls.__dict__.get(name)\n        if isinstance(obj, Static):\n            obj.__delete__(name)\n        else:\n            super(StaticType, cls).__delattr__(name)\n    def __getattribute__(cls, *args):\n        obj = super(StaticType, cls).__getattribute__(*args)\n        if isinstance(obj, Static):\n            obj = obj.__get__(cls, cls.__class__)\n        return obj\n    def __setattr__(cls, name, val):\n        # check if object already exists\n        obj = cls.__dict__.get(name)\n        if isinstance(obj, Static):\n            obj.__set__(name, val)\n        else:\n            super(StaticType, cls).__setattr__(name, val)\n</code></pre>\n\n<p>and in use:</p>\n\n<pre><code>class MyStatic(metaclass=StaticType):\n    """\n    Testing static vars\n    """\n    a = Static(9)\n    b = Static(12)\n    c = 3\n\nclass YourStatic(MyStatic):\n    d = Static(\'woo hoo\')\n    e = Static(\'doo wop\')\n</code></pre>\n\n<p>and some tests:</p>\n\n<pre><code>ms1 = MyStatic()\nms2 = MyStatic()\nms3 = MyStatic()\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nassert ms1.c == ms2.c == ms3.c == MyStatic.c\nms1.a = 77\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nms2.b = 99\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\nMyStatic.a = 101\nassert ms1.a == ms2.a == ms3.a == MyStatic.a\nMyStatic.b = 139\nassert ms1.b == ms2.b == ms3.b == MyStatic.b\ndel MyStatic.b\nfor inst in (ms1, ms2, ms3):\n    try:\n        getattr(inst, \'b\')\n    except AttributeError:\n        pass\n    else:\n        print(\'AttributeError not raised on %r\' % attr)\nms1.c = 13\nms2.c = 17\nms3.c = 19\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\nMyStatic.c = 43\nassert ms1.c == 13\nassert ms2.c == 17\nassert ms3.c == 19\n\nys1 = YourStatic()\nys2 = YourStatic()\nys3 = YourStatic()\nMyStatic.b = \'burgler\'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nys1.a = \'blah\'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\nys2.b = \'kelp\'\nassert ys1.b == ys2.b == ys3.b == YourStatic.b == MyStatic.b\nys1.d = \'fee\'\nassert ys1.d == ys2.d == ys3.d == YourStatic.d\nys2.e = \'fie\'\nassert ys1.e == ys2.e == ys3.e == YourStatic.e\nMyStatic.a = \'aargh\'\nassert ys1.a == ys2.a == ys3.a == YourStatic.a == MyStatic.a\n</code></pre>\n'}, {'answer_id': 41413059, 'author': 'jmunsch', 'author_id': 2026508, 'author_profile': 'https://Stackoverflow.com/users/2026508', 'pm_score': 2, 'selected': False, 'text': '<h1>Static Variables in Class factory python3.6</h1>\n<p>For anyone using a class factory with <strong>python3.6</strong> and up use the <code>nonlocal</code> keyword to add it to the scope / context of the class being created like so:</p>\n<pre><code>&gt;&gt;&gt; def SomeFactory(some_var=None):\n...     class SomeClass(object):\n...         nonlocal some_var\n...         def print():\n...             print(some_var)\n...     return SomeClass\n... \n&gt;&gt;&gt; SomeFactory(some_var=&quot;hello world&quot;).print()\nhello world\n</code></pre>\n'}, {'answer_id': 42392246, 'author': 'Mari Selvan', 'author_id': 5483135, 'author_profile': 'https://Stackoverflow.com/users/5483135', 'pm_score': 3, 'selected': False, 'text': '<p>Absolutely Yes,\n  Python by itself don\'t have any static data member explicitly, but We can have by doing so </p>\n\n<pre><code>class A:\n    counter =0\n    def callme (self):\n        A.counter +=1\n    def getcount (self):\n        return self.counter  \n&gt;&gt;&gt; x=A()\n&gt;&gt;&gt; y=A()\n&gt;&gt;&gt; print(x.getcount())\n&gt;&gt;&gt; print(y.getcount())\n&gt;&gt;&gt; x.callme() \n&gt;&gt;&gt; print(x.getcount())\n&gt;&gt;&gt; print(y.getcount())\n</code></pre>\n\n<p>output</p>\n\n<pre><code>0\n0\n1\n1\n</code></pre>\n\n<p>explanation</p>\n\n<pre><code>here object (x) alone increment the counter variable\nfrom 0 to 1 by not object y. But result it as "static counter"\n</code></pre>\n'}, {'answer_id': 46335281, 'author': 'Davis Herring', 'author_id': 8586227, 'author_profile': 'https://Stackoverflow.com/users/8586227', 'pm_score': 4, 'selected': False, 'text': '<p>One very interesting point about Python\'s attribute lookup is that it can be used to create "<a href="https://en.wikipedia.org/wiki/Virtual_function" rel="noreferrer">virtual</a> variables":</p>\n\n<pre><code>class A(object):\n\n  label="Amazing"\n\n  def __init__(self,d): \n      self.data=d\n\n  def say(self): \n      print("%s %s!"%(self.label,self.data))\n\nclass B(A):\n  label="Bold"  # overrides A.label\n\nA(5).say()      # Amazing 5!\nB(3).say()      # Bold 3!\n</code></pre>\n\n<p>Normally there aren\'t any assignments to these after they are created.  Note that the lookup uses <code>self</code> because, although <code>label</code> is static in the sense of not being associated with a <em>particular</em> instance, the value still depends on the (class of the) instance.</p>\n'}, {'answer_id': 53775598, 'author': 'Shagun Pruthi', 'author_id': 6136001, 'author_profile': 'https://Stackoverflow.com/users/6136001', 'pm_score': 3, 'selected': False, 'text': '<p>Yes, definitely possible to write static variables and methods in python.</p>\n\n<p><strong>Static Variables :</strong>\nVariable declared at class level are called static variable which can be accessed directly using class name.</p>\n\n<pre><code>    &gt;&gt;&gt; class A:\n        ...my_var = "shagun"\n\n    &gt;&gt;&gt; print(A.my_var)\n        shagun\n</code></pre>\n\n<p><strong>Instance variables:</strong> Variables that are related and accessed by instance of a class are instance variables.</p>\n\n<pre><code>   &gt;&gt;&gt; a = A()\n   &gt;&gt;&gt; a.my_var = "pruthi"\n   &gt;&gt;&gt; print(A.my_var,a.my_var)\n       shagun pruthi\n</code></pre>\n\n<p><strong>Static Methods:</strong> Similar to variables, static methods can be accessed directly using class Name. No need to create an instance. </p>\n\n<p>But keep in mind, a static method cannot call a non-static method in python.</p>\n\n<pre><code>    &gt;&gt;&gt; class A:\n   ...     @staticmethod\n   ...     def my_static_method():\n   ...             print("Yippey!!")\n   ... \n   &gt;&gt;&gt; A.my_static_method()\n   Yippey!!\n</code></pre>\n'}, {'answer_id': 58683325, 'author': 'Jay', 'author_id': 5387972, 'author_profile': 'https://Stackoverflow.com/users/5387972', 'pm_score': 2, 'selected': False, 'text': '<p>You can use a list or a dictionary to get "static behavior" between instances.</p>\n\n<pre><code>class Fud:\n\n     class_vars = {\'origin_open\':False}\n\n     def __init__(self, origin = True):\n         self.origin = origin\n         self.opened = True\n         if origin:\n             self.class_vars[\'origin_open\'] = True\n\n\n     def make_another_fud(self):\n         \'\'\' Generating another Fud() from the origin instance \'\'\'\n\n         return Fud(False)\n\n\n     def close(self):\n         self.opened = False\n         if self.origin:\n             self.class_vars[\'origin_open\'] = False\n\n\nfud1 = Fud()\nfud2 = fud1.make_another_fud()\n\nprint (f"is this the original fud: {fud2.origin}")\nprint (f"is the original fud open: {fud2.class_vars[\'origin_open\']}")\n# is this the original fud: False\n# is the original fud open: True\n\nfud1.close()\n\nprint (f"is the original fud open: {fud2.class_vars[\'origin_open\']}")\n# is the original fud open: False\n</code></pre>\n'}, {'answer_id': 61080153, 'author': 'Christopher Hoffman', 'author_id': 7497211, 'author_profile': 'https://Stackoverflow.com/users/7497211', 'pm_score': 2, 'selected': False, 'text': "<p>So this is probably a hack, but I've been using <code>eval(str)</code> to obtain an static object, kind of a contradiction, in python 3.</p>\n\n<p>There is an Records.py file that has nothing but <code>class</code> objects defined with static methods and constructors that save some arguments.  Then from another .py file I <code>import Records</code> but i need to dynamically select each object and then instantiate it on demand according to the type of data being read in.</p>\n\n<p>So where <code>object_name = 'RecordOne'</code> or the class name, I call <code>cur_type = eval(object_name)</code> and then to instantiate it you do <code>cur_inst = cur_type(args)</code>\nHowever before you instantiate you can call static methods from <code>cur_type.getName()</code> for example, kind of like abstract base class implementation or whatever the goal is.  However in the backend, it's probably instantiated in python and is not truly static, because eval is returning an object....which must have been instantiated....that gives static like behavior.</p>\n"}, {'answer_id': 61805905, 'author': 'Winter Squad', 'author_id': 8566159, 'author_profile': 'https://Stackoverflow.com/users/8566159', 'pm_score': 2, 'selected': False, 'text': '<p>If you are attempting to share a static variable for, by example, increasing it across other instances, something like this script works fine:</p>\n\n<pre><code># -*- coding: utf-8 -*-\nclass Worker:\n    id = 1\n\n    def __init__(self):\n        self.name = \'\'\n        self.document = \'\'\n        self.id = Worker.id\n        Worker.id += 1\n\n    def __str__(self):\n        return u"{}.- {} {}".format(self.id, self.name, self.document).encode(\'utf8\')\n\n\nclass Workers:\n    def __init__(self):\n        self.list = []\n\n    def add(self, name, doc):\n        worker = Worker()\n        worker.name = name\n        worker.document = doc\n        self.list.append(worker)\n\n\nif __name__ == "__main__":\n    workers = Workers()\n    for item in ((\'Fiona\', \'0009898\'), (\'Maria\', \'66328191\'), ("Sandra", \'2342184\'), (\'Elvira\', \'425872\')):\n        workers.add(item[0], item[1])\n    for worker in workers.list:\n        print(worker)\n    print("next id: %i" % Worker.id)\n</code></pre>\n'}, {'answer_id': 62960717, 'author': 'ganja', 'author_id': 13864415, 'author_profile': 'https://Stackoverflow.com/users/13864415', 'pm_score': 1, 'selected': False, 'text': '<p>Put it this way the static variable is created when a user-defined a class come into existence and the define a static variable it should follow the keyword self,</p>\n<pre><code>class Student:\n\n    the correct way of static declaration\n    i = 10\n\n    incorrect\n    self.i = 10\n</code></pre>\n'}, {'answer_id': 65918726, 'author': 'Vlad Bezden', 'author_id': 30038, 'author_profile': 'https://Stackoverflow.com/users/30038', 'pm_score': 4, 'selected': False, 'text': '<p>@dataclass definitions provide class-level names that are used to define the instance variables and the initialization method, <code>__init__()</code>. If you want class-level variable in <code>@dataclass</code> you should use <a href="https://docs.python.org/3/library/typing.html#typing.ClassVar" rel="noreferrer"><code>typing.ClassVar</code></a> type hint. The <code>ClassVar</code> type\'s parameters define the class-level variable\'s type.</p>\n<pre><code>from typing import ClassVar\nfrom dataclasses import dataclass\n\n@dataclass\nclass Test:\n    i: ClassVar[int] = 10\n    x: int\n    y: int\n    \n    def __repr__(self):\n        return f&quot;Test({self.x=}, {self.y=}, {Test.i=})&quot;\n</code></pre>\n<p>Usage examples:</p>\n<pre><code>&gt; test1 = Test(5, 6)\n&gt; test2 = Test(10, 11)\n\n&gt; test1\nTest(self.x=5, self.y=6, Test.i=10)\n&gt; test2\nTest(self.x=10, self.y=11, Test.i=10)\n</code></pre>\n'}, {'answer_id': 66255775, 'author': 'Sunil Garg', 'author_id': 2172547, 'author_profile': 'https://Stackoverflow.com/users/2172547', 'pm_score': 0, 'selected': False, 'text': '<p>Not like the <code>@staticmethod</code> but class variables are static method of class and are shared with all the instances.</p>\n<p>Now you can access it like</p>\n<pre><code>instance = MyClass()\nprint(instance.i)\n</code></pre>\n<p>or</p>\n<pre><code>print(MyClass.i)\n</code></pre>\n<p>you have to assign the value to these variables</p>\n<p>I was trying</p>\n<pre><code>class MyClass:\n  i: str\n</code></pre>\n<p>and assigning the value in one method call, in that case it will not work and will throw an error</p>\n<pre><code>i is not attribute of MyClass\n</code></pre>\n'}, {'answer_id': 68682495, 'author': 'alda78', 'author_id': 2161600, 'author_profile': 'https://Stackoverflow.com/users/2161600', 'pm_score': 4, 'selected': False, 'text': '<p>With Object datatypes it is possible. But with primitive types like  <code>bool</code>, <code>int</code>, <code>float</code> or <code>str</code> bahaviour is different from other OOP languages. Because in inherited class static attribute does not exist. If attribute does not exists in inherited class, Python start to look for it in parent class. If found in parent class, its value will be returned. When you decide to change value in inherited class, static attribute will be created in runtime. In next time of reading inherited static attribute its value will be returned, bacause it is already defined. Objects (lists, dicts) works as a references so it is safe to use them as static attributes and inherit them. Object address is not changed when you change its attribute values.</p>\n<p>Example with integer data type:</p>\n<pre><code>class A:\n    static = 1\n\n\nclass B(A):\n    pass\n\n\nprint(f&quot;int {A.static}&quot;)  # get 1 correctly\nprint(f&quot;int {B.static}&quot;)  # get 1 correctly\n\nA.static = 5\nprint(f&quot;int {A.static}&quot;)  # get 5 correctly\nprint(f&quot;int {B.static}&quot;)  # get 5 correctly\n\nB.static = 6\nprint(f&quot;int {A.static}&quot;)  # expected 6, but get 5 incorrectly\nprint(f&quot;int {B.static}&quot;)  # get 6 correctly\n\nA.static = 7\nprint(f&quot;int {A.static}&quot;)  # get 7 correctly\nprint(f&quot;int {B.static}&quot;)  # get unchanged 6\n</code></pre>\n<p>Solution based on <a href="https://pypi.org/project/refdatatypes/" rel="noreferrer">refdatatypes</a> library:</p>\n<pre><code>from refdatatypes.refint import RefInt\n\n\nclass AAA:\n    static = RefInt(1)\n\n\nclass BBB(AAA):\n    pass\n\n\nprint(f&quot;refint {AAA.static.value}&quot;)  # get 1 correctly\nprint(f&quot;refint {BBB.static.value}&quot;)  # get 1 correctly\n\nAAA.static.value = 5\nprint(f&quot;refint {AAA.static.value}&quot;)  # get 5 correctly\nprint(f&quot;refint {BBB.static.value}&quot;)  # get 5 correctly\n\nBBB.static.value = 6\nprint(f&quot;refint {AAA.static.value}&quot;)  # get 6 correctly\nprint(f&quot;refint {BBB.static.value}&quot;)  # get 6 correctly\n\nAAA.static.value = 7\nprint(f&quot;refint {AAA.static.value}&quot;)  # get 7 correctly\nprint(f&quot;refint {BBB.static.value}&quot;)  # get 7 correctly\n</code></pre>\n'}, {'answer_id': 69723203, 'author': 'HIMANSHU PANDEY', 'author_id': 14952627, 'author_profile': 'https://Stackoverflow.com/users/14952627', 'pm_score': 3, 'selected': False, 'text': '<p>Summarizing others\' answers and adding, there are many ways to declare Static Methods or Variables in <strong>python</strong>.<br></p>\n<h1>1. Using <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer">staticmethod()</a> as a decorator:</h1>\n<p>One can simply put a decorator above a method(function) declared to make it a static method. For eg.<br></p>\n<pre><code>class Calculator:\n    @staticmethod\n    def multiply(n1, n2, *args):\n        Res = 1\n        for num in args: Res *= num\n        return n1 * n2 * Res\n\nprint(Calculator.multiply(1, 2, 3, 4))              # 24\n</code></pre>\n<h1>2. Using <a href="https://docs.python.org/3/library/functions.html#staticmethod" rel="noreferrer">staticmethod()</a> as a parameter function:</h1>\n<p>This method can receive an argument which is of function type, and it returns a static version of the function passed. For eg.<br></p>\n<pre><code>class Calculator:\n    def add(n1, n2, *args):\n        return n1 + n2 + sum(args)\n\nCalculator.add = staticmethod(Calculator.add)\nprint(Calculator.add(1, 2, 3, 4))                   # 10\n</code></pre>\n<h1>3. Using <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer">classmethod()</a> as a decorator:</h1>\n<p>@classmethod has similar effect on a function as @staticmethod has, but\nthis time, an additional argument is needed to be accepted in the function (similar to self parameter for instance variables). For eg.<br></p>\n<pre><code>class Calculator:\n    num = 0\n    def __init__(self, digits) -&gt; None:\n        Calculator.num = int(\'\'.join(digits))\n\n    @classmethod\n    def get_digits(cls, num):\n        digits = list(str(num))\n        calc = cls(digits)\n        return calc.num\n\nprint(Calculator.get_digits(314159))                # 314159\n</code></pre>\n<h1>4. Using <a href="https://docs.python.org/3/library/functions.html#classmethod" rel="noreferrer">classmethod()</a> as a parameter function:</h1>\n<p>@classmethod can also be used as a parameter function, in case one doesn\'t want to modify class definition. For eg.<br></p>\n<pre><code>class Calculator:\n    def divide(cls, n1, n2, *args):\n        Res = 1\n        for num in args: Res *= num\n        return n1 / n2 / Res\n\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.divide(15, 3, 5))                  # 1.0\n</code></pre>\n<h1>5. Direct declaration</h1>\n<p>A method/variable declared outside all other methods, but inside a class is automatically static.<br></p>\n<pre><code>class Calculator:   \n    def subtract(n1, n2, *args):\n        return n1 - n2 - sum(args)\n\nprint(Calculator.subtract(10, 2, 3, 4))             # 1\n</code></pre>\n<h1>The whole program<br></h1>\n<pre><code>class Calculator:\n    num = 0\n    def __init__(self, digits) -&gt; None:\n        Calculator.num = int(\'\'.join(digits))\n    \n    \n    @staticmethod\n    def multiply(n1, n2, *args):\n        Res = 1\n        for num in args: Res *= num\n        return n1 * n2 * Res\n\n\n    def add(n1, n2, *args):\n        return n1 + n2 + sum(args)\n    \n\n    @classmethod\n    def get_digits(cls, num):\n        digits = list(str(num))\n        calc = cls(digits)\n        return calc.num\n\n\n    def divide(cls, n1, n2, *args):\n        Res = 1\n        for num in args: Res *= num\n        return n1 / n2 / Res\n\n\n    def subtract(n1, n2, *args):\n        return n1 - n2 - sum(args)\n    \n\n\n\nCalculator.add = staticmethod(Calculator.add)\nCalculator.divide = classmethod(Calculator.divide)\n\nprint(Calculator.multiply(1, 2, 3, 4))              # 24\nprint(Calculator.add(1, 2, 3, 4))                   # 10\nprint(Calculator.get_digits(314159))                # 314159\nprint(Calculator.divide(15, 3, 5))                  # 1.0\nprint(Calculator.subtract(10, 2, 3, 4))             # 1\n</code></pre>\n<p>Refer to <a href="https://www.python.org/doc/versions/" rel="noreferrer">Python Documentation</a> for mastering OOP in python.</p>\n'}, {'answer_id': 72141879, 'author': 'MusicalNinja', 'author_id': 3305998, 'author_profile': 'https://Stackoverflow.com/users/3305998', 'pm_score': 0, 'selected': False, 'text': '<h2>Class variable and allow for subclassing</h2>\n<p>Assuming you are not looking for a <em>truly</em> static variable but rather something pythonic that will do the same sort of job for consenting adults, then use a class variable.\nThis will provide you with a variable which all instances can access (and update)</p>\n<p><strong>Beware: Many of the other answers which use a class variable will break subclassing.</strong> You should avoid referencing the class directly by name.</p>\n<pre><code>from contextlib import contextmanager\n\nclass Sheldon(object):\n    foo = 73\n\n    def __init__(self, n):\n        self.n = n\n\n    def times(self):\n        cls = self.__class__\n        return cls.foo * self.n\n        #self.foo * self.n would give the same result here but is less readable\n        # it will also create a local variable which will make it easier to break your code\n    \n    def updatefoo(self):\n        cls = self.__class__\n        cls.foo *= self.n\n        #self.foo *= self.n will not work here\n        # assignment will try to create a instance variable foo\n\n    @classmethod\n    @contextmanager\n    def reset_after_test(cls):\n        originalfoo = cls.foo\n        yield\n        cls.foo = originalfoo\n        #if you don\'t do this then running a full test suite will fail\n        #updates to foo in one test will be kept for later tests\n</code></pre>\n<p>will give you the same functionality as using <code>Sheldon.foo</code> to address the variable and will pass tests like these:</p>\n<pre><code>def test_times():\n    with Sheldon.reset_after_test():\n        s = Sheldon(2)\n        assert s.times() == 146\n\ndef test_update():\n    with Sheldon.reset_after_test():\n        s = Sheldon(2)\n        s.updatefoo()\n        assert Sheldon.foo == 146\n\ndef test_two_instances():\n    with Sheldon.reset_after_test():\n        s = Sheldon(2)\n        s3 = Sheldon(3)\n        assert s.times() == 146\n        assert s3.times() == 219\n        s3.updatefoo()\n        assert s.times() == 438\n</code></pre>\n<p>It will also allow someone else to simply:</p>\n<pre><code>class Douglas(Sheldon):\n    foo = 42\n</code></pre>\n<p>which will also work:</p>\n<pre><code>def test_subclassing():\n    with Sheldon.reset_after_test(), Douglas.reset_after_test():\n        s = Sheldon(2)\n        d = Douglas(2)\n        assert d.times() == 84\n        assert s.times() == 146\n        d.updatefoo()\n        assert d.times() == 168 #Douglas.Foo was updated\n        assert s.times() == 146 #Seldon.Foo is still 73\n\ndef test_subclassing_reset():\n    with Sheldon.reset_after_test(), Douglas.reset_after_test():\n        s = Sheldon(2)\n        d = Douglas(2)\n        assert d.times() == 84 #Douglas.foo was reset after the last test\n        assert s.times() == 146 #and so was Sheldon.foo\n</code></pre>\n<p>For great advice on things to watch out for when creating classes check out Raymond Hettinger\'s video <a href="https://www.youtube.com/watch?v=HTLu2DFOdTg" rel="nofollow noreferrer">https://www.youtube.com/watch?v=HTLu2DFOdTg</a></p>\n'}, {'answer_id': 74501446, 'author': 'Kai - Kazuya Ito', 'author_id': 8172439, 'author_profile': 'https://Stackoverflow.com/users/8172439', 'pm_score': 0, 'selected': False, 'text': '<p>You can create <strong>the class variable <code>x</code></strong>, <strong>the instance variable <code>name</code></strong>, <strong>the instance method <code>test1(self)</code></strong>, <strong>the class method <code>test2(cls)</code></strong> and <strong>the static method <code>test3()</code></strong> as shown below:</p>\n<pre class="lang-py prettyprint-override"><code>class Person:\n    x = &quot;Hello&quot; # Class variable\n\n    def __init__(self, name):\n        self.name = name # Instance variable\n    \n    def test1(self): # Instance method\n        print(&quot;Test1&quot;)\n\n    @classmethod\n    def test2(cls): # Class method\n        print(&quot;Test2&quot;)\n        \n    @staticmethod\n    def test3(): # Static method\n        print(&quot;Test3&quot;)\n</code></pre>\n<p>I explain about <strong>class variable</strong> in <a href="https://stackoverflow.com/questions/707380/how-to-access-static-class-variables-in-python/74493657#74493657"><strong>my answer</strong></a> and <strong>class method</strong> and <strong>static method</strong> in <a href="https://stackoverflow.com/questions/136097/classmethod-vs-staticmethod-in-python/74470227#74470227"><strong>my answer</strong></a> and <strong>instance method</strong> in <a href="https://stackoverflow.com/questions/46230482/what-is-an-instance-method-in-python/74482579#74482579"><strong>my answer</strong></a>.</p>\n'}]
['https://Stackoverflow.com/questions/68645', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2246/']