[Tutor] class variables

eryksun eryksun at gmail.com
Sat Dec 21 14:41:17 CET 2013


On Sat, Dec 21, 2013 at 2:14 AM, Steven D'Aprano <steve at pearwood.info> wrote:
>
> (Sometimes, people will call them "members", especially if they are used
> to C#. The meaning here is member as in an arm or leg, as in
> "dismember", not member in the sense of belonging to a group.)

A Python object isn't just a fixed-size block of data with members at
fixed offsets. It stores its data dynamically in a dict.

That said, CPython objects do have members as an implementation
detail, including class-defined __slots__. The member_descriptor type
is used to access members as attributes.

For example, the read-only __base__ attribute of a class uses the
following descriptor:

    >>> vars(type)['__base__']
    <member '__base__' of 'type' objects>

> Suppose we ask Python for "polly.colour". Python looks at the instance
> polly, and checks to see if it has an instance attribute called "polly".
> If it does, we're done. But if it doesn't, Python doesn't give up
> straight away, it next checks the class of polly, which is Parrot. Does
> Parrot have an attribute called "polly"? Yes it does, so that gets
> returned.

It first has to check Parrot and its base classes (in Method
Resolution Order, i.e. Parrot.__mro__) for a data descriptor (e.g. a
property) named "colour". An instance can't override a data
descriptor.

> So unlike *getting* an attribute, which searches both the instance
> and the class, *setting* or *deleting* an attribute stops at the
> instance.

Setting and deleting an attribute also has to start by searching the
class and bases for data descriptors.


More information about the Tutor mailing list