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

K

Kenneth McDonald

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:
.... def __init__(self, a, b):
.... str.__init__(a)
.... self.b = b
.... Traceback (most recent call last):

(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 :) )

.... def __init__(self, x):
.... str.__init__(x)
....
Is it possible to circumvent the above restrictions?

Thanks,
Ken
 
L

Larry Bates

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
1

Uses old UserString class.

HTH,
Larry Bates
Syscon, Inc.
 
R

Russell Blau

Kenneth McDonald said:
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:

... def __init__(self, a, b):
... str.__init__(a)
... self.b = b
...
Traceback (most recent call last):

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:
def __new__(cls, a, b):
return str.__new__(cls, a)
def __init__(self, a, b):
self.b = b
'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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,578
Members
45,052
Latest member
LucyCarper

Latest Threads

Top