Mutability problem when subclassing tuple

Discussion in 'Python' started by Edward C. Jones, Feb 19, 2004.

  1. # What restrictions are there when subclassing "tuple" or other
    # types that create immutable objets?

    # I want this class to contain "(1, 2)".
    class simple(tuple):
    def __init__(self, text):
    tuple.__init__(self, [1, 2])

    # "simple2" works, therefore "simple" has a mutability problem.
    class simple2(list):
    def __init__(self, text):
    list.__init__(self, [1, 2])

    # Here is an example that shows what I am trying to do.
    # I want to create the tuple in "example" within "__init__" by
    # processing "text". In this case the tuple should be "(1, 2)".
    class example(tuple):
    def __init__(self, text):
    alist = self.process(text)
    tuple.__init__(alist)

    def process(self, text):
    return [1, 2]

    if __name__ == '__main__':
    print simple('abc') # Prints "('a', 'b', 'c')".
    print simple2('abc') # Prints "[1, 2]".
    print example('abc') # Prints "('a', 'b', 'c')".
     
    Edward C. Jones, Feb 19, 2004
    #1
    1. Advertisements

  2. Edward C. Jones

    Aahz Guest

    In article <40342544$0$3105$>,
    Edward C. Jones <> wrote:
    >
    ># What restrictions are there when subclassing "tuple" or other
    ># types that create immutable objets?


    You need to set the values with __new__().
    --
    Aahz () <*> http://www.pythoncraft.com/

    "Argue for your limitations, and sure enough they're yours." --Richard Bach
     
    Aahz, Feb 19, 2004
    #2
    1. Advertisements

  3. Shalabh Chaturvedi, Feb 19, 2004
    #3
    1. Advertisements

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. Michal Mikolajczyk
    Replies:
    1
    Views:
    1,013
    Larry Bates
    Apr 20, 2004
  2. Gregor Horvath

    Why tuple with one item is no tuple

    Gregor Horvath, Mar 15, 2005, in forum: Python
    Replies:
    37
    Views:
    1,181
    Antoon Pardon
    Mar 30, 2005
  3. Steve
    Replies:
    1
    Views:
    1,315
    Fredrik Lundh
    Dec 13, 2005
  4. Replies:
    6
    Views:
    327
    Duncan Booth
    Feb 23, 2007
  5. Davy
    Replies:
    3
    Views:
    2,060
    Wildemar Wildenburger
    Nov 7, 2007
  6. named tuple mutability

    , May 14, 2008, in forum: Python
    Replies:
    10
    Views:
    554
    Bruno Desthuilliers
    May 15, 2008
  7. Jeff Nyman
    Replies:
    8
    Views:
    650
    Terry Reedy
    Jun 5, 2008
  8. Frank Millman
    Replies:
    5
    Views:
    500
    Hrvoje Niksic
    Mar 31, 2010
Loading...