initializing mutable class attributes

Dan Perl dperl at rogers.com
Wed Sep 1 14:58:42 EDT 2004


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