Created
June 28, 2013 08:07
-
-
Save inesusvet/5883212 to your computer and use it in GitHub Desktop.
Задача в том чтобы иметь объяснение почему в строке 4 нет ошибки, в то время как в строке 8 значения различаются
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| In [1]: class Foo(object): | |
| ...: attr = {'initial_state': True} | |
| ...: def bar_class(self): | |
| ...: self.attr['initial_state'] = False | |
| ...: def bar_instance(self): | |
| ...: self.attr = {'initial_state': False} | |
| ...: | |
| In [2]: foo = Foo() | |
| In [3]: foo.bar_class() | |
| In [4]: assert Foo.attr == foo.attr == {'initial_state': False} | |
| In [5]: class Foo(object): | |
| ...: attr = {'initial_state': True} | |
| ...: def bar_class(self): | |
| ...: self.attr['initial_state'] = False | |
| ...: def bar_instance(self): | |
| ...: self.attr = {'initial_state': False} | |
| ...: | |
| In [6]: foo = Foo() | |
| In [7]: foo.bar_instance() | |
| In [8]: Foo.attr, foo.attr | |
| Out[8]: ({'initial_state': True}, {'initial_state': False}) | |
| In [9]: |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
После создания объекта, у
fooнет атрибутаattr. Поэтому, когда мы вызываем в 3-й строкеbar_class,self.attr— это на самом делеself.__class__.attr, который интерпретатор находит в дереве предков у класса Foo, который мы и меняем. Вbar_instanceу нашего объекта появляется свой атрибутattr, и теперь при вызовеself.attrинтерпретатор возвращает объект, на который ссылаетсяself.attr.