Created
June 15, 2017 09:34
-
-
Save juanarrivillaga/ab85dfcf70feff2d61a7a25175586aef to your computer and use it in GitHub Desktop.
This file contains 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
# So, consider: | |
>>> class SomeClass: | |
... var = 'foo' | |
... | |
>>> x = SomeClass() | |
>>> x.var | |
'foo' | |
>>> SomeClass.var | |
'foo' | |
# So far so good. But *who* does `var` belong to? Well, as the name class-variable implies, it belongs to *the class*. This is obvious if we check the class namespace vs the instance namespace: | |
>>> x.__dict__ | |
{} | |
>>> SomeClass.__dict__ | |
mappingproxy({'__module__': '__main__', 'var': 'foo', '__dict__': <attribute '__dict__' of 'SomeClass' objects>, '__weakref__': <attribute '__weakref__' of 'SomeClass' objects>, '__doc__': None}) | |
# Now, what happens if we change `x.var`? Does `SomeClass.var` see that change? | |
>>> x.var = 'bar' | |
>>> SomeClass.var | |
'foo' | |
>>> x.var | |
'bar' | |
# And one final look at the namespaces makes it clear, | |
>>> x.__dict__ | |
{'var': 'bar'} | |
>>> SomeClass.__dict__ | |
mappingproxy({'__module__': '__main__', 'var': 'foo', '__dict__': <attribute '__dict__' of 'SomeClass' objects>, '__weakref__': <attribute '__weakref__' of 'SomeClass' objects>, '__doc__': None}) | |
>>> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment