[Python-Dev] Class Methods

Thomas Heller thomas.heller at ion-tof.com
Mon Apr 23 10:33:40 EDT 2001


> [Thomas Heller]
> > ...
> > There are (even in the standard python library) usage
> > patterns going like this:
> >
> > class X:
> >     _inited = 0
> >     def __init__(self, ...):
> >         if not _inited:
> >             <code to set some class attributes>
> >         ....
> >
> > This is really not instance but class initialization,
> > and it is deferred until the first instance has been
> > created. What if someone need the (calculated) class
> > attributes before this?
>
[Tim Peters]
> I *suspect* you're reading the code incorrectly, but hard to say since that
> snippet doesn't make sense.  If the actual test looks like
>
>     if not X._inited:
>
> then, yes, maybe so.

My apologies. My example code did not work, and you
are right with your explanation.

There are cases however (although not in the python library),
where class attributes do not only provide _default_ values
for the instance, but are shared among _all_ instances of this class.

Here is my actual example:

I want to define C Structure-like classes, which can be used to wrap
memory blocks, and allow access via attribute names.

Take the following C code:

struct POINT{
    int x, y;
};

which I would like to define in python in this way:

class POINT(Structure):
    _names = "x", "y"
    _format = "ii"     # specified in the way the struct-module uses

and use in this way:

p = POINT(10, 20)
p.x # would return 10
p.x = 100
p._getaddr() # would return the address of the memory block containing
             # a struct POINT.

POINT.size_in_bytes
  or
POINT.size_in_bytes() # would return the same as the C code sizeof(struct POINT)

I would like to retrieve the size_in_bytes attribute _before_
the first instance of POINT is created, so I cannot calculate
this in the first __init__() call, a magic class method,
automatically called just after the class creation, would come
very handy.

Thomas





More information about the Python-list mailing list