首页 > 解决方案 > 从 txt 文件中获取数组并在 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 的参数。

标签: pythonarraysobjectconstructorarguments

解决方案


trips[0]只是一个字符串,这就是*trips[0]导致 36 个参数(每个字符)的原因。您需要先在,.

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

为了摆脱 之后的空格split(','),您可以执行以下操作:

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

推荐阅读