因此,我目前正在使用类作为课程项目的一部分,并希望使用从文本文件中获取的数组作为参数。下面是我试过的,有人能给我一些建议吗
class Trips:
destination = ""
dep_date = ""
airline = ""
ret_date = ""
def __init__(self, destination, dep_date, airline, ret_date):
self.destination = destination
self.dep_date = dep_date
self.airline = airline
self.ret_date = ret_date
def get_trips():
tripsdb = open("tripsdb.txt")
content = tripsdb.read()
tripsdb.close()
trips = content.split("\n")
trips.pop(len(trips)-1)
return trips
trips = get_trips()
print(trips)
#this prints ['Lisbon, 28.02.2020, TAP, 03.03.2020', 'Fortaleza, 20.06.2020, TAP, 25.06.2020'] all trips in text file
print(trips[0])
#this prints Lisbon, 28.02.2020, TAP, 03.03.2020 the content of the first array
trip1 = Trips(trips[0])
print(trip1)
#this prints Traceback (most recent call last):
File "class.py", line 25, in <module>
trip1 = Trips(trips[0])
TypeError: __init__() missing 3 required positional arguments: 'dep_date', 'airline', and 'ret_date'
trip1 = Trips(*trips[0])
print(trip1)
Traceback (most recent call last):
File "class.py", line 25, in <module>
trip1 = Trips(*trips[0])
TypeError: __init__() takes 5 positional arguments but 36 were given
最终我想要它做的是允许数组成为Trips的参数
trips[0]
只是一个字符串,这就是为什么*trips[0]
会产生36个参数(每个字符)。您需要首先在,
上拆分字符串Trips(*trips[0].split(','))
应该按预期工作为了去除
split(',')
之后的空白,可以执行以下操作:相关问题 更多 >
编程相关推荐