【发布时间】:2020-01-06 20:23:54
【问题描述】:
我正在为一个课程项目开发一个简单的网络应用程序,它是一个基本的旅行跟踪器。 用户可以输入出发日期、目的地、航空公司和返回日期。用户将输入多个行程。 此 UI 保存为 txt 文件。 作为项目的一部分,我还必须使用类。选择的类是 Trips,参数是 UI。 然后我建立了一个倒计时来显示出发日期或出发日期之后的时间。我希望它使用类对象和参数。 我正在寻找一种方法来自动化 UI 中的对象名称和参数。 下面是代码,第 24 行显示了我希望自动实现的行。
import datetime
#set class
class Trips:
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
#get trips
def get_trips():
tripsdb = open("tripsdb.txt")
content = tripsdb.read()
tripsdb.close()
trips = content.split("$$$")
trips.pop(len(trips)-1)
return trips
#countdown days to departure using datetime
def countdown():
trips = get_trips()
trip1 = Trips(*trips[2].split(",")) #need to automate
get_date = trip1.dep_date
depart_date = datetime.datetime.strptime(get_date, "%d.%m.%Y")
#set todays date
nowdate = datetime.datetime.now()
#difference in seconds
count = int((depart_date-nowdate).total_seconds())
#divide into days
days = count/86400
# set as int to round and string to concatenate, use abs to remove "-"
if int(days) > 0:
return(str(int(days)) + " days left to departure")
elif int(days) == 0:
return "You depart today!"
else:
return (str(abs(int(days))) + " days since your departure")
print(countdown())
我已经尝试了各种循环和拉链,但根据我的尝试,总是遇到各种错误。我尝试使用 for 循环创建一个数组,该循环将返回trip_num = [trip0,trip1,trip2],以便获得变量名称。
def get_array():
array = []
num = -1
trips = get_trips()
for trip in trips:
num += 1
array += ["trip " + str(num)]
return array
trip_num = get_array()
然后我想基本上将 trip_num 中的第一项连接到 trips 的第一项,以返回类似于 trip1=destination、dep_date、航空公司,ret_date 等等。明白我的意思了吗?
【问题讨论】:
-
首先你应该显示你得到的错误。我们无法运行您的代码,也无法在您的脑海中看到这些错误。
-
顺便说一句:我会使用名称
Trip,因为它只能保留一次行程。我会使用for-loop 创建许多Trip,我会保留在列表中。 -
您可以使用
.pop(-1)而不是.pop(len(trips)-1)来获取最后一项 -
啊哈@furas,我对你缺乏读心能力感到失望! ;) 因此,根据我的尝试,我遇到了几个错误...我尝试使用 for 循环创建一个数组,该数组将返回trip_num = [trip0,trip1,trip2],以便获得变量名字。然后我想基本上将trip_num 中的第一项连接到trips 的第一项,以返回类似于trip1=destination、dep_date、airline、ret_date 的内容。明白我的意思了吗?
-
@furas,也感谢您提供的其他提示,我才刚刚开始,所以我正处于与我所拥有的知识混在一起并希望最好的阶段。希望我能及时解决其中的一些错误......
标签: python arrays object parameters