[Tutor] class variables

eryksun eryksun at gmail.com
Fri Dec 20 13:09:38 CET 2013


On Fri, Dec 20, 2013 at 5:20 AM, Alan Gauld <alan.gauld at btinternet.com> wrote:
>
> Similarly if you have a name defined within the instance it will use that if
> not it will look in the class.

An instance can generally shadow class attributes, except properties
and other data descriptors defined by the class are given precedence
when looking up attributes:

    >>> instance = Class()
    >>> Class.pi = property(lambda s: 3.14)

    >>> instance.pi
    3.14
    >>> instance.pi = 4
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    AttributeError: can't set attribute

The property is used even if you manually assign pi in the instance dict:

    >>> vars(instance)['pi'] = 4
    >>> vars(instance)
    {'pi': 4}
    >>> instance.pi
    3.14


More information about the Tutor mailing list