gpt4 book ai didi

python - 如何修复Python中的 "AttributeError: type object has no attribute"?

转载 作者:行者123 更新时间:2023-12-01 08:24:33 26 4
gpt4 key购买 nike

我在预设代码中添加一些代码来检查时间可用性,即 session 时间是否符合建议的时间表。但是,我不断收到以下错误。有人可以给我一些建议吗?非常感谢您抽出时间。

预设代码:

from datetime import datetime
class Meeting:
def __init__(self, start_time, end_time):
self.start_time = start_time
self.end_time = end_time

我的代码:

def check_availability(meetings, proposed_time): 
meeting_start = Meeting.datetime.start_time.hour
meeting_end = Meeting.datetime.end_time.hour
ok_time = datetime.proposed_time.hour
if meeting_start < ok_time < meeting_end:
return True
else:
return False

meetings = [Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11,
0, 0)), Meeting(datetime(2018, 8, 1, 15, 0, 0), datetime(2018, 8, 1, 16, 0,
0)), Meeting(datetime(2018, 8, 2, 9, 0, 0), datetime(2018, 8, 2, 10, 0, 0))]

print(check_availability(meetings, datetime(2018, 8, 1, 12, 0, 0)))
print(check_availability(meetings, datetime(2018, 8, 1, 10, 0, 0)))

最佳答案

您的代码引发了此异常:

AttributeError: type object 'Meeting' has no attribute 'datetime'

在这一行:

meeting_start = Meeting.datetime.start_time.hour

Python 告诉你 Meeting class 没有名为 datetime 的属性。这是真的:Meeting class是一个用于制作 session 对象(或实例)的工厂,这些对象有start_timeend_time属性,通过将日期时间实例传递给Meeting来设置的__init__方法。这些属性可以这样访问:

>>> meeting = Meeting(datetime(2018, 8, 1, 9, 0, 0), datetime(2018, 8, 1, 11, 
0, 0))
>>> print(meeting.start_time)
2018-08-01 09:00:00
>>> print(meeting.end_time)
2018-08-01 11:00:00

您的 check_availability 函数正在传递一个 session 列表,因此您需要循环该列表以检查是否有任何 session 与建议的 session 时间冲突。

def check_availability(meetings, proposed_time):
# Loop over the list of meetings; "meeting"
# is the meeting that you are currently inspecting.
for meeting in meetings:
# if proposed_time is between meeting.start_time
# and meeting.end_time, return False
# If you get through the list without returning False
# then the proposed time must be ok, so return True.

关于python - 如何修复Python中的 "AttributeError: type object has no attribute"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54358613/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com