我在Python中做了一些OOP,當用戶輸入一個元組作爲參數之一時遇到了麻煩。下面的代碼:元組麻煩
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) + ")"
我試圖想初始化英寸爲0,將有助於東西出來,但沒有奏效。元組也不支持索引,因此該選項也不存在。我覺得答案很簡單,我只是在推翻它。我使用的測試代碼:
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)
我的代碼工作時int
輸入,但同樣,我似乎無法弄清楚當一個元組輸入如預期。有任何想法嗎?
元組支持索引。 –
問題標題中有一個星際迷航引用可以從我這裏得到upvote :) – krock
@PadraicCunningham(從什麼時候開始'a =(2,0); print(a [0])'拋出IndexError?元組支持索引.. )對不起,忘了我說過的話,我誤解了你的評論......我的道歉! – Spirine