SpecialistOff.NET / Вопросы / Статьи / Фрагменты кода / Резюме / Метки / Помощь / Файлы

Назад

Static Fields


Метки: python

An excellent example of the subtleties of initialization is static fields in classes.

::
>>> class Foo(object):
...   x = "a"
...
>>> Foo.x
'a'
>>> f = Foo()
>>> f.x
'a'
>>> f2 = Foo()
>>> f2.x
'a'
>>> f2.x = 'b'
>>> f.x
'a'
>>> Foo.x = 'c'
>>> f.x
'c'
>>> f2.x
'b'
>>> Foo.x = 'd'
>>> f2.x
'b'
>>> f.x
'd'
>>> f3 = Foo()
>>> f3.x
'd'
>>> Foo.x = 'e'
>>> f3.x
'e'
>>> f2.x
'b'

If you assign, you get a new one. If it’s modifiable, then unless you assign you are working on a singleton. So a typical pattern is:

class Foo:
    something = None # Static: visible to all classes
    def f(self, x):
        if not self.something:
            self.something = [] # New local version for this object
        self.something.append(x)

This is not a serious example because you would naturally just initialize something in Foo‘s constructor.