subclassing built-in types
Gabriel Cooper
gabriel.cooper at mediapulse.com
Mon May 24 17:08:19 EDT 2004
I have data in lists of dictionaries with an accompanying array that I
would like to be able to treat as a normal array of strings so that it
will work with predefined functions that work with such, but I would
also like to have the ability to add and manipulate attributes, such as
each field's padding for output of the corresponding data:
(Running on RHFC2)
Python 2.3.3 (#1, May 7 2004, 10:31:40)
[GCC 3.3.3 20040412 (Red Hat Linux 3.3.3-7)] on linux2
[...]
IDLE 1.0.2
>>> class myString(str):
def __init__(self, thestring, padding=0, *args,**kargs):
str.__init__(self,thestring, *args,**kargs)
self.padding = padding
>>> x = myString("hello")
>>> x
'hello'
>>> x.padding
0
>>> x = myString("hello",40)
Traceback (most recent call last):
File "<pyshell#205>", line 1, in -toplevel-
x = myString("hello",40)
TypeError: str() takes at most 1 argument (2 given)
>>> x = myString("hello")
>>> x.padding = 50
>>> x
'hello'
>>> x.padding
50
>>>
(in other words, I can do it in two steps, not one. I also tried
UserString and string as superclasses.)
More information about the Python-list
mailing list