Now we proceed to embellish our class with some attributes.
We can just proceed to add an attribute to the class
C we defined earlier:
>>> class C: pass >>> C <class __main__.C at 0x0352DC38> >>> dir(C) ['__doc__', '__module__'] >>> C.foo = "Peanut!" >>> dir(C) ['__doc__', '__module__', 'foo']
dir(C) shows us the attributes of a Python object. Python classes (remember
that they are objects in their own right...) come with
some of the default ones you see above. By just assigning a value to
C now has a new attribute
foo we defined here is what's known as a class variable. It belongs to
the class itself as opposed to instances of the class.
>>> x=C() >>> y=C() >>> C.foo 'Peanut!' >>> x.foo # defaults to the class attribute of the same name 'Peanut!' >>> y.foo 'Peanut!' >>> C.foo="Nuts!" >>> x.foo 'Nuts!' >>> y.foo 'Nuts!'
You can also create these class variables within the class definition itself which is essentially equivalent to the above:
>>> class C: foo="Peanut!" >>> C.foo 'Peanut!' >>> x=C() >>> x.foo 'Peanut!'
>>> x.bar="Peas!" >>> x.bar 'Peas!' >>> y.bar Traceback (most recent call last): File ..., line 1, in <module> y.bar AttributeError: C instance has no attribute 'bar' >>> C.bar Traceback (most recent call last): File ..., line 1, in <module> C.bar AttributeError: class C has no attribute 'bar'
Assigning to an attribute of an instance which happens to have the same name as an attribute of its class will shadow the class attribute.
>>> x.foo="Pianos!" >>> C.foo 'Nuts!' >>> x.foo 'Pianos! >>> y.foo # 'y' instance was not assigned a 'foo' attribute of its own 'Nuts! >>> del(x.foo) >>> x.foo 'Nuts!' >>> del(C.foo) # now all 'foo' attributes are gone >>> x.foo Traceback (most recent call last): .... in <module> x.foo AttributeError: C instance has no attribute 'foo'