Is it possible to have instance variables in subclasses of builtins?
Kenneth McDonald
kenneth.m.mcdonald at sbcglobal.net
Tue Jun 15 18:21:45 EDT 2004
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