The class has its own dictionary,
external.__dict__
. This is where
external.i
is stored.
Each instance of the class also has its own dictionary
self.__dict__
. This is where
self.i
is stored.
When one writes
external.i
, python searches the member
i
in the class' dictionary and if it does not find one, it searches in the ancestor classes. When one writes
self.i
, python searches in the instance's dictionary and if it does not find one, it searches in the class' dictionary, then in the ancestor classes.
If you have a C++ background, you might expect a different behavior for class members. I once wrote a function to simulate a C++ static field in a python class
def static_cpp():
from functools import partial
_default = object()
def _helper_static_cpp(container, value = _default):
if value is not _default:
container[0] = value
return container[0]
def static_cpp(initializer = None):
"""Declarator to imitate a c++ static field in a class (with accessor).
>>> class A(object):
... foo = static_cpp(1.24)
...
>>> print( A.foo() )
1.24
>>> A.foo(555)
>>> print( A.foo() )
555
>>> a = A()
>>> print( a.foo() )
555
>>> a.foo(666)
>>> print( A.foo() )
666
"""
return partial(_helper_static_cpp, [initializer])
return static_cpp
static_cpp = static_cpp()