Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trouble with Tuples

Tags:

python

oop

tuples

I'm doing some OOP in Python and I'm having trouble when the user inputs a tuple as one of the arguments. Here's the code:

class Height:
    def __init__(self,ft,inch=0):
        if isinstance(ft,tuple):
            self.feet = ft
            self.inches = inch
        elif isinstance(ft,int):
            self.feet = ft // 12
            self.inches = ft % 12
    def __str__(self):
        return str(self.feet) + " Feet " + str(self.inches) + " Inches"
    def __repr__(self):
        return "Height (" + str(self.feet * 12 + self.inches) + ")"

I tried thought initializing the inch to 0 would help thing out but that didn't work. Tuples also don't support indexing so that option was also non-existent. I feel like the answer is simple and I'm just overthinking it. The test code that I'm using is:

from height import *
def test(ht):
    """tests the __str__, __repr__, and to_feet methods for the height
   Height->None"""
    #print("In inches: " + str(ht.to_inches()))
    #print("In feet and inches: " + str(ht.to_feet_and_inches()))
    print("Convert to string: " + str(ht))
    print("Internal representation: " + repr(ht))
    print()
print("Creating ht1: Height(5,6)...")
ht1 = Height(5,6)
test(ht1)
print("Creating ht2: Height(4,13)...")
ht2 = Height(4,13)
test(ht2)
print("Creating ht3: Height(50)...")
ht3 = Height(50)
test(ht3)

My code works as expected when an int is input but, again, I can't seem to figure it out when a tuple is input. Any ideas?

like image 232
Trevor Scott Cohen Avatar asked Jul 09 '26 00:07

Trevor Scott Cohen


1 Answers

Are you really being passed a tuple? It looks to me that your constructor should simply be:

def __init__(self, ft, inch=0):
   self.ft = int(ft)
   self.inch = int(inch)

That works if you create your object with any of these (because you have a default value for the inch argument):

foo = Height(6)
bar = Height(6, 3)
baz = Height("5", 3)

etc. Note that in the second and third instances, you still aren't being passed a tuple. In order to actually receive a tuple, you'd need to call it like this:

foo2 = Height((6, 3))

or use the '*' operator in the constructor declaration.

like image 126
Gil Hamilton Avatar answered Jul 11 '26 15:07

Gil Hamilton



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!