我在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