【发布时间】:2020-04-21 07:10:22
【问题描述】:
所以我目前正在使用类作为课程项目的一部分,并希望使用从文本文件中获取的数组作为参数。以下是我尝试过的,有人可以提出任何帮助吗?
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是一个列表,而不是一个数组 - 在 Python 中。
标签: python arrays object constructor arguments