Is it possible to have instance variables in subclasses of builtins?
lbates at swamisoft.com
Wed Jun 16 00:45:06 CEST 2004
The following might work for you:
from UserString import UserString
def __init__(self, x, y, z):
>>> x=b('h', 1, 2)
Uses old UserString class.
"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
> Is it possible to circumvent the above restrictions?
More information about the Python-list