Dictionaries and lists defined directly under the class definition act as static (e.g. this question)
How come other variables such as integer do not?
>>> class Foo():
bar=1
>>> a=Foo()
>>> b=Foo()
>>> a.bar=4
>>> b.bar
1
>>> class Foo():
bar={}
>>> a=Foo()
>>> b=Foo()
>>> a.bar[7]=8
>>> b.bar
{7: 8}
A variable is declared as static to get the latest and single copy of its value; it means the value is going to be changed somewhere.
Static variables are used to keep track of information that relates logically to an entire class, as opposed to information that varies from instance to instance.
Someone may eventually come up with a statically typed version of Python but it's highly unlikely it will catch on. The reason Python is so popular is because it is extremely easy to learn and very flexible for programming. Static typing would compromise these qualities.
They are all class variables. Except for when you assigned a.bar=4
creating an instance variable. Basically Python has a lookup order on attributes. It goes:
instance -> class -> parent classes in MRO order (left to right)
So if you have
class Foo(object):
bar = 1
This is a variable on the class Foo. Once you do
a = Foo()
a.bar = 2
you have created a new variable on the object a
with the name bar
. If you look at a.__class__.bar
you will still see 1, but it is effectively hidden due to the order mentioned earlier.
The dict you created is at the class-level so it is shared between all instances of that class.
When you make the assignment
>>> a.bar=4
you are rebinding the Foo.bar
name to 4
, which is a new instance of an integer. On the other hand,
>>> a.bar[7]=8
Does not rebind Foo.bar
to anything different, and simply modifies the dictionary that the name refers to.
If you do
>>> a.bar = {7: 8}
then you will rebind Foo.bar
to a new dictionary.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With