0

I am playing with inheritance with python but got stuck when I try to modify the properties of a tuple. This is what I did:

class MyTuple(tuple):
    def __init__(self):
        super().__init__()
    def add(self,number):
        self = tuple(list(self)+[number])

Now when I use

x = MyTuple()
x.add(23)

x doesn't changed to (23), but is still ()! Am I doing something wrong or does this has to do something with hashing?

Anmol Gautam
  • 949
  • 1
  • 12
  • 27
  • 3
    Possible duplicate of [Python subclass tuple object with ability to reinstantiate self internally](https://stackoverflow.com/questions/4306557/python-subclass-tuple-object-with-ability-to-reinstantiate-self-internally) – EsotericVoid Aug 10 '17 at 10:15

1 Answers1

2

You're doing something wrong that has nothing to do with hashing. Tuples are immutable, which means they do not change. When calling tuple you create a new tuple. You then assigned self, which is a function argument, and therefore a local variable. All that does is lose track of which object the add method was called on. The method then returns, causing the new tuple to be deleted.

By the way, why did you even make lists? Tuples can be added.

Yann Vernier
  • 15,414
  • 2
  • 28
  • 26
  • as per my knowledge tuples cannot be added, how do you add them? – Anmol Gautam Aug 10 '17 at 10:48
  • @YannVernier: they do not change because they were defined this way (methods for mutability raising errors or not existing), but he added a function that would recreate a tuple to replace self. Why would it not work? Because he doesn't return self? Otherwise, there is nothing in tuple definition that prevent self itself from being changed. – Ando Jurai Aug 10 '17 at 10:58
  • @Tarptaeya: You just add these with + operation. – Ando Jurai Aug 10 '17 at 11:08
  • It's the typical confusion between names and objects. `self` is the name of a local variable, which holds a reference; the object it refers to is remains when you make `self` point to another. `x` is another name for that original object and completely independent of `self`. The object itself also never changes because not only didn't anyone try, it is immutable which means incapable of change. – Yann Vernier Aug 10 '17 at 12:00
  • You add (concatenate actually, but we reused the + symbol) tuples exactly like lists, the only difference is the syntax to create a single-entry tuple: `x+(23,)` because the parenthesis wouldn't make a tuple without the comma. – Yann Vernier Aug 10 '17 at 12:09