【问题标题】:How to set object name and parameters from UI in python如何在 python 中从 UI 设置对象名称和参数
【发布时间】: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


【解决方案1】:

我不知道我是否理解你的问题,但我会这样写。

  • 在课堂上,我将两个日期都转换为 datetime 对象。
  • 我将countdown 作为类中的方法,而不是外部函数。
  • 我不使用变量trip1trip2 等将所有行程都保留在列表中。

.

# --- classes ---

class Trip:

    def __init__(self, destination, dep_date, airline, ret_date):
        self.destination = destination
        self.airline = airline
        self.dep_date = datetime.datetime.strptime(dep_date, "%d.%m.%Y")
        self.ret_date = datetime.datetime.strptime(ret_date, "%d.%m.%Y")

    def countdown(self):
        nowdate = datetime.datetime.now()

        seconds = (self.dep_date-nowdate).total_seconds()
        days = seconds//86400 # divide and round to integer

        if days > 0:
            return "{} days left to departure".format(days)
        elif days < 0:
            return "{} days since your departure".format(-days) 
        else:
            return "You depart today!"

# --- functions ---

def read_trips():
    tripsdb = open("tripsdb.txt")
    content = tripsdb.read()
    tripsdb.close()

    trips = content.split("$$$")
    trips.pop(-1)
    #trips = content.split("$$$")[:-1] in one line using `slicing`

    # convert to list of objects Trip
    all_trips = []
    for trip in trips:
        all_trips.append( Trip(*trip.split(",")) )

    return all_trips

def write_trips(all_trips):
    pass
    #TODO: write it

# --- main ---

all_trips = read_trips()

for trip in all_trips:
    print('Destination:', trip.destination)
    print('Airline:', trip.airline)
    print('Countdown:', trip.countdown())
    print('---')

【讨论】:

  • 噢噢噢! @furas!你是一个传奇!.append! 这就是我所缺少的!你清理其余部分的方式很棒。我曾考虑过将倒计时作为一种方法,很高兴看到它也在那里。非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-27
  • 1970-01-01
  • 2023-03-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多