首页 > 解决方案 > 类型错误:+ 不支持的操作数类型:“浮点”和“时间”

问题描述

我试图让它工作,似乎问题是当我尝试添加一个小时和一个小数表示时间(例如 .75 等于 45 分钟)。我想我需要在init () 中添加一些东西,但是我不确定什么会解决它。浮标?

class Time():

    def __init__(self,a=0.0,b=0.0):
        self.hour = a
        self.minute = b
        self.hour_dec = a-int(a)
        self.total_hour = self.hour - self.hour_dec
        self.extraMin = self.hour_dec * 60
        self.total_min = self.minute + self.extraMin
        if self.total_min > 60:
            self.total_min= self.total_min - 60
            self.total_hour += 1

    def __str__(self):
        return str(self.total_hour)+" hours, "+str(self.total_min)+" minutes "


    def __add__(self, other): #Brad suggested the if statement to get this part to work
        if isinstance(other,int):
            newHour = self.total_hour + other
            newMinute = self.total_min
            return Time(newHour,newMinute)

        else:
            newHour = self.total_hour + other.total_hour
            newMinute = self.total_min  + other.total_min
            return Time(newHour,newMinute)

def main():
    time0= Time()
    print(time0)
    time1 = Time(6)
    print(time1)
    time2 = Time(3,30)
    print(time2)
    time3 = Time(30,75)
    print(time3)
    time4 = Time(3.5)
    print(time4)
    print(time3 + time4)
    print(time3)
    print(time1 + 10)
    print(.75 + time2)

main() 

标签: pythonfloating-pointinteger

解决方案


推荐阅读