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

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

  3. Shalabh Chaturvedi, Feb 19, 2004
    #3
    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. ex_ottoyuhr

    Mutability of function arguments?

    ex_ottoyuhr, Dec 8, 2005, in forum: Python
    Replies:
    17
    Views:
    477
    Fredrik Lundh
    Dec 8, 2005
  2. gigs

    list mutability

    gigs, Feb 18, 2008, in forum: Python
    Replies:
    1
    Views:
    241
    John Machin
    Feb 18, 2008
  3. named tuple mutability

    , May 14, 2008, in forum: Python
    Replies:
    10
    Views:
    453
    Bruno Desthuilliers
    May 15, 2008
  4. cnb
    Replies:
    1
    Views:
    216
    Alan G Isaac
    Aug 26, 2008
  5. kj
    Replies:
    4
    Views:
    422
    Arnaud Delobelle
    Oct 7, 2010
Loading...

Share This Page