James
James

Reputation: 2795

How to access tuple's elements in a class that inherits it

Suppose I'm trying to write a class that acts like a tuple in every way except one: when you print it, any values above 10 are replaced by 10. I would usually do this by having a class that inherits tuple but changing the __str__ magic method. However, I do not know how tuple's __str__ magic method is written so I'm unsure of how I can access each individual element to check if it is above 10 to print it.

Are there any solutions to this (if its relevant, each of these tuples will only have two fields)?

class sampleClass(tuple):

    def __str__(self):
        return "({0}, {1})".format(min(elem1IsomehowGet, 10), min(elem2IsomehowGet, 10))
>>> x = sampleClass((3, 15))
>>> print x
(3, 10)
>>> x[1]
15

Upvotes: 1

Views: 1748

Answers (1)

A.J. Uppal
A.J. Uppal

Reputation: 19264

I think this is what you're looking for:

class sampleClass:
    def __init__(self, tup):
            self.tup = tup
    def __str__(self): #To print it
            return str(tuple([item if item <= 10 else 10 for item in self.tup])) #List comprehension to replace x > 10 with 10, then convert to a tuple, then surround with quotes so __str__ accepts it
    def __getitem__(self, ind): #To access by index e.g. x[1], x[-1] etc.
            return self.tup[ind]

>>> from sampleClass import sampleClass as sc
>>> x = sc((3, 15))
>>> x[1]
15
>>> print x
(3, 10)
>>> 




          Note: I replaced all values greater than 10 with 'H', which is what you wrote in your question, however, in your question
                                                                                 you replaced it with a 10.



                                                         Note: JK, you edited your question
                            enter image description here

Upvotes: 2

Related Questions