subclassing built-in types

Discussion in 'Python' started by Gabriel Cooper, May 24, 2004.

  1. 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.)
    Gabriel Cooper, May 24, 2004
    #1
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Emiliano Molina

    Subclassing built-in types

    Emiliano Molina, Aug 25, 2004, in forum: Python
    Replies:
    3
    Views:
    306
    Emiliano Molina
    Aug 26, 2004
  2. Jane Austine
    Replies:
    12
    Views:
    446
    Nick Coghlan
    Feb 24, 2005
  3. MonkeeSage

    Subclassing built-in classes

    MonkeeSage, Oct 5, 2006, in forum: Python
    Replies:
    12
    Views:
    549
    Theerasak Photha
    Oct 11, 2006
  4. Alona
    Replies:
    2
    Views:
    651
  5. kj
    Replies:
    2
    Views:
    238
Loading...

Share This Page