"Kenneth McDonald" <kenneth.m.mcdonald@sbcglobal.net> wrote in message
news:slrnccutjp.3qk.kenneth.m.mcdonald@g4.gateway. 2wire.net...[color=blue]
> 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:
>[color=green][color=darkred]
> >>> class a(str):[/color][/color]
> ... def __init__(self, a, b):
> ... str.__init__(a)
> ... self.b = b
> ...[color=green][color=darkred]
> >>> x = a("h", "g")[/color][/color]
> Traceback (most recent call last):
> File "<stdin>", line 1, in ?
> TypeError: str() takes at most 1 argument (2 given)[color=green][color=darkred]
> >>>[/color][/color][/color]
The problem is that "str" is an immutable type. Therefore, to change the
constructor, you need to override the __new__ method. See
http://www.python.org/2.2.1/descrintro.html#__new__
Here's an example:
[color=blue][color=green][color=darkred]
>>> class two(str):[/color][/color][/color]
def __new__(cls, a, b):
return str.__new__(cls, a)
def __init__(self, a, b):
self.b = b
[color=blue][color=green][color=darkred]
>>> z = two("g", "h")
>>> z[/color][/color][/color]
'g'[color=blue][color=green][color=darkred]
>>> z.b[/color][/color][/color]
'h'
Note that both arguments (a and b) get passed to both the __new__ and
__init__ methods, and each one just ignores the one it doesn't need.
--
I don't actually read my hotmail account, but you can replace hotmail with
excite if you really want to reach me.