subclassing built-in types

From: Gabriel Cooper (gabriel.cooper_at_mediapulse.com)
Date: 05/24/04


Date: Mon, 24 May 2004 17:08:19 -0400
To: python-list@python.org

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.)



Relevant Pages

  • Re: Checking if a variable is a dictionary
    ... strings or nested tuples or dictionaries and then convert values to a ... then handle tuples (or the exception), then strings which should work ... python dicts can hold any kind of object. ...
    (comp.lang.python)
  • Fast Data Comparison (dict v. list. v string)
    ... many comparisons to fixed-size lists of fixed-length strings. ... my implementation uses dictionaries to store each string. ... all I have to do to compare the two ... it appears that strings are constant as I can't assign individual ...
    (comp.lang.python)
  • Re: language design question
    ... - why is lennot a member function of strings? ... but having all standard operations as a method seems more regular, and allows a simple chained operation format of a series of method calls, instead of alternating prefix function calls, and post-fix method invocations; ... dictionaries, ...
    (comp.lang.python)
  • Re: Common Python Idioms
    ... I agree completely (in the sense that dictionaries shouldn't be iterable directly). ... Probably even more strongly, at least every time I see some code where someone iterates over the keys, only to use the key to look up the value. ... iteration over strings happens in my code only when a pass a string where I should have passed a list of strings. ...
    (comp.lang.python)
  • len() and PEP 3000
    ... I suggest that at least lists, tupples, sets, dictionaries and strings ...
    (comp.lang.python)