initializing mutable class attributes
Dan Perl
dperl at rogers.com
Wed Sep 1 15:38:41 EDT 2004
I found a small hole in the initial code suggestion and I fixed it. Try and
find the difference:
class test(object):
def __new__(typ, *args, **kwargs):
obj = object.__new__(typ)
obj.attr1 = 666
typ.__init__(obj, *args, **kwargs)
return obj
class derived(test):
def __init__(self, arg1, arg2):
self.attr2 = arg1
self.attr3 = arg2
d = derived(111, 222)
print d.attr1, d.attr2
print isinstance(d, test)
So, what do people think about it? Alex, would this be good for a recipe in
the Python Cookbook?
Dan
"Dan Perl" <dperl at rogers.com> wrote in message
news:CZoZc.159227$UTP.62107 at twister01.bloor.is.net.cable.rogers.com...
> After all this discussion, what do people think about this code?
> class test(object):
> def __new__(typ):
> obj = object.__new__(typ)
> obj.attr1 = 666
> return obj
>
> class derived(test):
> def __init__(self):
> self.attr2 = 111
>
> d = derived()
> print d.attr1, d.attr2
> print isinstance(d, test)
>
> The output:
> 666 111
> True
>
> At least it works. The 'test' superclass defines an instance attribute
> attr1 and it initializes it with a default. The 'derived' subclass
inherits
> the attribute (implicitly, BTW ;-)) and that happens without an __init__
in
> the superclass that would have to be invoked in the subclass.
>
> Dan
>
>
More information about the Python-list
mailing list