在elif中尝试除外,无法按预期工作

对于这部分代码,即使在if obj.overtime_approve == False:. 在该条件之后不会执行以下行。我无法理解原因。

这里obj来自一个方法,它可以是dictobject。因此我添加了一个try块。我的代码有什么问题吗?

elif given_date.weekday() == 4:
            try:
                if obj.overtime_approve == False:
                    print("yep")
                    friday_ot_hours = 0
                    holiday_ot_hours = 0
                    normal_hours = 0
                    normal_ot_hours = 0
                    total_hours = normal_ot_hours + normal_hours
            except Exception as e:
                if obj['overtime_approve'] == False:
                    print("yes")
                    friday_ot_hours = 0
                    holiday_ot_hours = 0
                    normal_hours = 0
                    normal_ot_hours = 0
                    total_hours = normal_ot_hours + normal_hours

编辑:

最初的代码是这样的。

elif given_date.weekday() == 4 and obj.overtime_approve == False:
            friday_ot_hours = 0
            holiday_ot_hours = 0
            normal_hours = 0
            normal_ot_hours = 0
            total_hours = normal_ot_hours + normal_hours

但是obj可以是<class 'dict'>or的类型<class 'apps.employee.models.UpdatedPunchRawDataProcesses'>

因此我添加了 try except 块来解决这个问题。有没有什么有效的方法可以做到这一点?

回答

在这种情况下,您可能希望使用isinstance来测试您正在使用的对象类型。

if isinstance(obj, dict):
    over_time = obj['overtime_approve']
elif isinstance(obj, UpdatedPunchRawDataProcesses):  # Replace this with whatever your class actually is
    over_time = obj.overtime_approve
else:
    raise TypeError("obj should only be dict or apps.employee.models.UpdatedPunchRawDataProcesses")

if over_time == False:
    friday_ot_hours = 0
    holiday_ot_hours = 0
    normal_hours = 0
    normal_ot_hours = 0
    total_hours = normal_ot_hours + normal_hours


以上是在elif中尝试除外,无法按预期工作的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>