subclassing built-in types

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Gabriel Cooper

    subclassing built-in types

    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[color=blue][color=green][color=darkred]
    >>> class myString(str):[/color][/color][/color]
    def __init__(self, thestring, padding=0, *args,**kargs):
    str.__init__(se lf,thestring, *args,**kargs)
    self.padding = padding

    [color=blue][color=green][color=darkred]
    >>> x = myString("hello ")
    >>> x[/color][/color][/color]
    'hello'[color=blue][color=green][color=darkred]
    >>> x.padding[/color][/color][/color]
    0[color=blue][color=green][color=darkred]
    >>> x = myString("hello ",40)[/color][/color][/color]

    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)[color=blue][color=green][color=darkred]
    >>> x = myString("hello ")
    >>> x.padding = 50
    >>> x[/color][/color][/color]
    'hello'[color=blue][color=green][color=darkred]
    >>> x.padding[/color][/color][/color]
    50[color=blue][color=green][color=darkred]
    >>>[/color][/color][/color]

    (in other words, I can do it in two steps, not one. I also tried
    UserString and string as superclasses.)

Working...