class external(threading.Thread):
i = 0
def __init__(self, dir_q, result_q):
super(external, self).__init__()
then right after "super", I write:
self.i = 5
--external.i returns 0 (from another object)
external.i = 5
--external.i returns 5 (from another object)
What is the difference, if only one instance of external exists?
By the way, self.i returns 5 if executed inside of a method from this instance in either way. If the instances sees self.i equal to external.i, why do other classes see external.i different that what this sees as self.i?
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()