gpt4 book ai didi

python - 元组的问题

转载 作者:太空宇宙 更新时间:2023-11-03 13:41:36 25 4
gpt4 key购买 nike

我在 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 时,我的代码按预期工作,但同样,当输入元组时,我似乎无法弄清楚。有什么想法吗?

最佳答案

你真的被传递了一个元组吗?在我看来,您的构造函数应该只是:

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

如果你用这些中的任何一个创建你的对象,这就有效(因为你有一个默认值的 inch 参数):

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

等请注意,在第二个和第三个实例中,仍然没有向您传递元组。为了实际接收元组,您需要这样调用它:

foo2 = Height((6, 3))

或在构造函数声明中使用“*”运算符。

关于python - 元组的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30019049/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com