从txt文件获取数组并在python中设置为构造函数参数

2024-09-27 00:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

因此,我目前正在使用类作为课程项目的一部分,并希望使用从文本文件中获取的数组作为参数。下面是我试过的,有人能给我一些建议吗

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的参数


Tags: selfdateinitcontentthisdestinationclassprint
1条回答
网友
1楼 · 发布于 2024-09-27 00:22:38

trips[0]只是一个字符串,这就是为什么*trips[0]会产生36个参数(每个字符)。您需要首先在,上拆分字符串

Trips(*trips[0].split(','))应该按预期工作

为了去除split(',')之后的空白,可以执行以下操作:

trip_data = [v.strip() for v in trips[0].split(',')]
trip1 = Trips(*trip_data)

相关问题 更多 >

    热门问题