frozenset/subclassing/keyword args
Bengt Richter
bokr at oz.net
Mon Oct 31 14:59:34 EST 2005
On Mon, 31 Oct 2005 19:31:33 GMT, "Mark E. Fenner" <Hobbes2176 at yahoo.com> wrote:
>Hello all,
>
>I was migrating some code from sets.ImmutableSet to frozenset and noticed
>the following:
>
>******code********
>#!/usr/bin/env python
>
>from sets import ImmutableSet
>
>
>class MSet1(ImmutableSet):
> def __init__(self, iterArg, myName="foo"):
> ImmutableSet.__init__(self, iterArg)
> self.name = myName
>
>
>class MSet2(frozenset):
> def __init__(self, iterArg, myName="foo"):
> frozenset.__init__(self, iterArg)
> self.name = myName
>
>
>m1 = MSet1([1,2,3], myName = "donkey")
>print m1
>print m1.name
>
>m2 = MSet2([1,2,3], myName = "kong")
>print m2
>print m2.name
>*********end code**********
>
>*********run**********
>MSet1([1, 2, 3])
>donkey
>Traceback (most recent call last):
> File "./setTest.py", line 22, in ?
> m2 = MSet2([1,2,3], myName = "kong")
>TypeError: frozenset() does not take keyword arguments
>*********end run********
>
>I'm missing something and couldn't find it in the docs.
Without researching it, I would guess that you have to override __new__
so as not to pass through the myName arg to the otherwise inherited and
called-with-all-arguments __new__ of the base class. You could take care
of the myName arg in the __new__ method too (by temporarily binding the
instance returned by frozenset.__new__ and assigning the name attribute
before returning the instance), or you can define __init__ to do that part.
See many various posted examples of subclassing immutable types.
Regards,
Bengt Richter
More information about the Python-list
mailing list