Pablo Riera
Pablo Riera

Reputation: 359

Python subclassing tuple with custom new

I wanted to make a class that mimics a tuple class but with some extra properties, for example a custom new.

The custom new works, but I couldn't figure out how to combine the member variables with the tuple inheritance.

I tried many different ways but I prefer to post just a simple skeleton to see if someone can guide me. Thanks in advance

class tupla(tuple):
    x = 0
    y = None

    def __new__(self, *args):

        if len(args)==1:
            self.y = args[0]

        if len(args)==2:
            self.x = args[0]
            self.y = args[1]        

        return tuple.__new__(tupla, ( self.x, self.y))


a = tupla(2)
print a

a.x = 1
print a

The output is of course,

(0, 2)

(0, 2)

and not (1,2) as is intended.

UPDATE:

It was not a good idea to use a tuple to do this as the answers clarify. Nevertheless it would very helpful if there is a way to do the same purpose with a list for example.

class lista(list):
    x = 0
    y = None

    def __init__(self,*args):
        print 'init'

        if len(args)==1:
            self.y = args[0]

        if len(args)==2:
            self.x = args[0]
            self.y = args[1]

        super(lista,self).__init__( [self.x, self.y] )

a = lista(2)
print a
a.x = 1
print a

Now the output is

[0, 2]

[0, 2]

Upvotes: 0

Views: 73

Answers (2)

BrenBarn
BrenBarn

Reputation: 251383

Setting self.x = args[0] doesn't mean changing self.x will update the tuple value. The tuple itself is still immutable, and self.x is a totally independent piece of data.

You could write a method or a property that will look up its value by using the tuple data, but there's no way you can make the change the underlying tuple data after the tuple is created. If you want something mutable, don't inherit from tuple.

Upvotes: 1

Eric
Eric

Reputation: 97571

tuples are immutable, therefore it does not make sense to make a mutable subclass

Upvotes: 1

Related Questions