[Python-Dev] Class Methods

Tim Peters tim.one at home.com
Sat Apr 21 19:51:13 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?

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.  But if it looks like

    if not self._inited:

then it's probably aiming at something quite different from class attribute
fiddling.  Whenever you see

    class X:
        attr = whatever
        ...
        def f(self):
            ...
            ... self.attr ...

it's *most likely* the case that the class author is *exploiting* that
self.attr will resolve to X.attr if self doesn't have its own attr.  This is
a memory-saving trick for attrs that *normally* have the same value across
most instances.  By letting self.attr defer to X.attr, the instance doesn't
have to burn space in its own dict to record attr's value, for so long as the
instance is happy to use the common value.  *Binding* to self.attr gives the
instance its own value for attr when the common value is not acceptable, and
then a later reference to self.attr picks that up instead of the class value.

Anyway, please point to some specific code in the std library that you think
is doing class-attr fiddling of the kind you're talking about.  Offhand I
don't recall any (but know lots of places that use the trick I just
described).





More information about the Python-list mailing list