Mutability problem when subclassing tuple

E

Edward C. Jones

# 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')".
 

Ask a Question

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

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,764
Messages
2,569,565
Members
45,041
Latest member
RomeoFarnh

Latest Threads

Top