In Python:

class myClass:
    istat = 111 #exists as soon as import class
    def __init__(self):
        print("in ctor")
        self.iauto = 222 #does not exist until instance created
mc1 = myClass()
mc2 = myClass()

In C++:

class myClass
    static int istat;
    int iauto;
myClass mc1, mc2;

I am trying to refresh my C++ and learn Python. It is interesting to compare them. Would the following be correct (regarding static class members of each language?)

  • Python: class members are by default static, and values can be accessed from either class or instances of class, but propagating a change through all instances only happens if class value is changed, if member in an instance is changed it becomes essentially a new member for that instance which masks the previous class member. Only static members are defined in class, to create an automatic variable create it in the constructor, it is only defined in instances of the class but class does not know it. Essentially class is being redefined for each instance of the class.

  • C++: class members are by default automatic. If declared static, value can be changed either through class (myClass::istat) or through instance (mc1.istat) and will propagate to all instances in that space. both static and auto members are defined in the class and all instances of the class, no class redefinition.

Yes, your statements are correct. Here is how you could implement the cpp static field behavior in python using an accessor function instead of an attribute

from __future__ import print_function
from functools import partial

# preliminary definitions

_default = object()

def _helper_static_cpp(container, value = _default):
    if value is _default:
        return container[0]
        container[0] = value

def static_cpp(initializer = None):
    return partial(_helper_static_cpp, [initializer])

# class example imitating a cpp static field with an accessor function

class A(object):
    istat = static_cpp(111)

if __name__ == '__main__':
    a = A()
    print(A.istat(), a.istat())
    print(A.istat(), a.istat())
    print(A.istat(), a.istat())
    b = A()
    print(A.istat(), a.istat(), b.istat())

""" my output -->
111 111
112 112
113 113
114 114 114
nice help
This question has already been answered. Start a new discussion instead.