initializing mutable class attributes

Dan Perl dperl at rogers.com
Wed Sep 1 20:17:22 EDT 2004


"David Bolen" <db3l at fitlinxx.com> wrote in message
news:u3c21wnbq.fsf at fitlinxx.com...
> "Dan Perl" <dperl at rogers.com> writes:
>
> > After all this discussion, what do people think about this code?
>
> On face value, I'd question why you're going through the extra effort.
> I may be missing the point in such a small example, but just having an
> __init__ in the base class that subclasses are supposed to call seems
> simpler.
>
> If you're just trying to find some way to have default attributes that can
> be used from subclasses without calling __init__, I'd probably just use
> class level definitions.  For example:

That is exactly what I'm trying to do, and in the initial posting of the
thread I was mentioning an initialization exactly like yours, but at the
same time I was pointing out that an initialization like that works only for
immutable attributes and not for mutable attributes, hence the need for the
__init__.  Or doing it in __new__ as I showed in the new code.

>           - - - - - - - - - - - - - - - - - - - - - - - - -
> Python 2.3.4 (#53, May 25 2004, 21:17:02) [MSC v.1200 32 bit (Intel)] on
win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class Test(object):
> ...     attr1 = 666
> ...
> >>> class Derived(Test):
> ...     def __init__(self):
> ...         self.attr2 = 111
> ...
> >>> d = Derived()
> >>> print d.attr1, d.attr2
> 666 111
> >>> print isinstance(d, Test)
> True
> >>>
>           - - - - - - - - - - - - - - - - - - - - - - - - -
>
> -- David





More information about the Python-list mailing list