Why does this work?

Terry Reedy tejarex at yahoo.com
Wed Mar 27 10:04:20 EST 2002


"a.clarke11" <a.clarke11 at pop.ntlworld.com> wrote in message
news:3CA1BB93.FC00D40D at pop.ntlworld.com...
> Hi
> I defined a class, and made an instance. The class sis not have a
> def__init__() line.

A class statement may optionally have a body that defines *class*
attributes (members and methods).  The body may optionally include an
__init__(self, args) method, which is mostly used for initialing
*instance* attributes immediately after the creation of a new (and
blank) instance.  When you try to read instance.name, the interpreter
first looks in the instance dictionary for instance attribute 'name'.
If it does not find it, it then looks in the class dictionary for
class attribute 'name'.  (And if there are base classes, it will look
thru their dicts also if necessary.)

> In the class, I defined a function  f(x) and an list
> object X.tiles. Why can I later call instancename.f, and
> instancename.tiles?

Because that is how Python classes work, as explained above.

Terry J. Reedy








More information about the Python-list mailing list