Is it possible to have instance variables in subclasses of builtins?

Larry Bates lbates at swamisoft.com
Wed Jun 16 00:45:06 CEST 2004


The following might work for you:

from UserString import UserString
class b(UserString):
    def __init__(self, x, y, z):
        self.y=y
        self.z=z
        self.x=x
        UserString.__init__(self, x)
        return

>>> x=b('h', 1, 2)
>>> x.z
2
>>> x.y
1
>>> x.x
'h'
>>> len(x)
1

Uses old UserString class.

HTH,
Larry Bates
Syscon, Inc.


"Kenneth McDonald" <kenneth.m.mcdonald at sbcglobal.net> wrote in message
news:slrnccutjp.3qk.kenneth.m.mcdonald at g4.gateway.2wire.net...
> I've recently used subclasses of the builtin str class to good effect.
> However, I've been unable to do the following:
>
> 1) Call the constructor with a number of arguments other than
> the number of arguments taken by the 'str' constructor.
>
> 2) Create and use instance variables (eg. 'self.x=1') in
> the same way that I can in a 'normal' class.
>
> As an example of what I mean, here's a short little session:
>
> >>> class a(str):
> ...     def __init__(self, a, b):
> ...             str.__init__(a)
> ...             self.b = b
> ...
> >>> x = a("h", "g")
> Traceback (most recent call last):
>   File "<stdin>", line 1, in ?
>   TypeError: str() takes at most 1 argument (2 given)
> >>>
>
> (hmm, on reflection, I shouldn't have used 'a' as a
> parameter to __init__--but that's merely bad
> style, not the cause of the error :-) )
>
> On the other hand, this example works:
>
> >>> class b(str):
> ...     def __init__(self, x):
> ...             str.__init__(x)
> ...
> >>> x = b("h")
> >>> x
> 'h'
> >>>
>
> Is it possible to circumvent the above restrictions?
>
> Thanks,
> Ken





More information about the Python-list mailing list