无法弄清楚为什么我会收到 typeError 'unsupported operand type(s) for -: 'int' and 'str' '

yungben

我在 15 分钟前发布了关于这个问题的帖子,但被告知没有足够的代码来说明问题是什么,所以这次我已经包含了整个内容。

问题出在 process_rental 函数中的 self.__r_miles += (new_odo - self.__odometer) 行中。我知道根据错误和特定行, self.__odometer 是一个字符串。但对于我的生活,我无法弄清楚为什么。我假设它是显而易见的,但我只是盯着它看了太久而没有注意到。

我相信我已经在需要时将所有内容都放入 int 中,但显然我在某个地方搞砸了。

 class Fleet(object):
    fleetcount = 0
    car_desc = "DMC DeLorean"
    daily_rate = 100
    maxfleet = 10
    
    def get_vin(self):
        return self.__vin
    def get_year(self):
        return self.__year
    def get_odometer(self):
        return self.__odometer
    def set_odometer(self, miles):
        if miles>self.__odometer:
            self.__odometer = miles
    def get_r_miles(self):
        return self.__r_miles
    def get_r_days(self):
        return self.__r_days
    def get_rentals(self):
        return self.__rentals
    
    def __init__(self, vin, typ, year, color, odometer, r_miles = 0, r_days = 0, rentals = 0 ):
        self.__vin = vin
        self.__type = typ
        self.__year = year
        self.color = color
        self.__odometer = odometer
        self.__r_miles = r_miles
        self.__r_days = r_days
        self.__rentals = rentals
        Fleet.fleetcount += 1
        
    def process_rental(self, new_odo, days):
        self.__rentals += 1
        self.__r_days += days
        self.__r_miles += (new_odo - self.__odometer)
        self.set_odometer(new_odo)
        
    def calc_bill(self,new_odo, days): 
        return days * Fleet.daily_rate
    
    def calc_age(self, curr_yr):
        age = curr_yr - self.__year
        return age
    
    def sell_car(self,curr_yr):
        if self.calc_age(curr_yr)>3 or self.__odometer>50000:
            return True
        else:
            return False
        
    def print_summary(self):
        print("VIN:", self.__vin, "Make:",Fleet.car_desc, "Year:", self.__year, "Color:", self.color, "Odometer:", self.__odometer, "\n")
        
    def print_metrics(self, curr_yr):
        age = curr_yr - self.__year
        rmpy = self.__r_miles/age
        rdpy = self.__r_days/age
        rpy = self.__rentals/age
        mpr = self.__r_miles/self.__rentals
        dpr = self.__r_days/self.__rentals
        print("METRICS FOR CAR WITH VIN", self.__vin, "ARE AS FOLLOWS")
        print("Average rental miles per year:", rmpy)
        print("Average rental days per year:", rdpy)
        print("Average times rented per year:", rpy)
        print("Average miles per rental:", mpr)
        print("Average days per rental:", dpr, "\n")
    
    def fleet_left(self):
        remaining = Fleet.maxfleet - Fleet.fleetcount
        if remaining>0:
            return remaining
        else:
            return 0
    
    def __str__(self):
        return self.__vin + "," + self.__type + "," + self.__year + "," + self.__odometer + "," + self.color + "," + self.__r_miles + "," + self.__r_days + "," + self.__rentals
        
class Truck(Fleet):
    daily_rate = 85
    mile_rate = .5
    def calc_bill(self, new_odo, days): 
        miles = new_odo - self.__odometer
        return (miles * Truck.mile_rate) + (days * Truck.daily_rate)


with open("fleet.txt", "r") as myfile:
    next(myfile)
    fleet = {}
    for line in myfile:
         v, ty, y, o, c, rm, rd, r = line.strip().split(",")
         if ty == "C":
            fleet[v] = Fleet(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
         else:
            fleet[v] = Truck(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))

totalrev = 0
with open("transaction.txt", "r") as myfile:
    for line in myfile:
        trans = line.strip().split(",")
        if trans[1] == "R":
            totalrev += fleet[trans[0]].calc_bill(int(trans[2]), int(trans[3]))
            fleet[trans[0]].process_rental(int(trans[2]), int(trans[3]))
        elif trans[1] == "S":
            fleet[trans[0]].set_odometer(int(trans[2]))
        elif trans[1] == "P":
            fleet[trans[0]].color = trans[2]
            
yr = int(input("What is the current year? "))
sell_list = []
for obj in fleet:
    if obj.sell_car(yr) == True:
        sell_list.append(obj.get_vin())

rem = Fleet.fleet_left()

print("Total Revenue:", totalrev)
print("VINs of vehicles that should be sold:", sell_list)
print("Additional number of vehicles that can be acquired:", rem)

with open("updated_fleet.txt", "w") as myfile:
    for obj in fleet:
        outline = obj.__str__()
        myfile.write(outline)
    myfile.close()
尼尔·戈弗雷·庞恰诺

这就是你所说的产生错误

self.__r_miles += (new_odo - self.__odometer)

具体来说

new_odo - self.__odometer

错误是:

unsupported operand type(s) for -: 'int' and 'str'

这意味着这self.__odometer是一个字符串。所以你有:

  • 将其初始化为字符串值
  • 将其值更改为某处的字符串

检查设置的代码部分self.__odometer并确保分配的值始终为 int。您可能没有将某些内容强制转换为 int 例如,self.__odometer = trans[0]而不是self.__odometer = int(trans[0]).

这是错误的根源。

v, ty, y, o, c, rm, rd, r = line.strip().split(",")
if ty == "C":
    fleet[v] = Fleet(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
else:
    fleet[v] = Truck(v, ty, int(y), int(o), c, int(rm), int(rd), int(r))
#                                           ^ You didn't cast the 5th argument, which is for odometer

line.strip().split(",")产生的字符串。然后,您直接使用它来初始化odometer第 5 个参数:

class Fleet:
    def __init__(self, vin, typ, year, color, odometer, r_miles = 0, r_days = 0, rentals = 0 ):
        #                                     ^ 5th argument

您只传递了 string c相反,将它转换为 int first int(c)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

為什麼我會收到“TypeError: unsupported operand type(s) for -: 'str' and 'str'”錯誤?

使用旋转轮得到:TypeError: unsupported operand type(s) for +=: 'int' and 'str'

我正在製作計算器,問題出在第 42 行 TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'int'

我有这个错误:TypeError: unsupported operand type(s) for *: 'int' and 'NoneType'

geopy.distance.geodesic() 但它说 TypeError: unsupported operand type(s) for +=: 'int' and 'tuple'

当 df 包含字符串时计算 Pandas pct_change 获取错误:TypeError: unsupported operand type(s) for /: 'float' and 'str'

为什么我会收到 TypeError: 'int' object not callable in a micro:bit MicroPython 程序?

无法弄清楚为什么这给了我TypeError

Python:TypeError:无法连接“str”和“int”

无法弄清楚为什么 int(" ") 表现得很奇怪

我收到TypeError:只能将str(而不是“ int”)连接到str

如果我输入错误的选项,我会收到此错误(TypeError: 'str' object is not callable)

为什么我会收到这个 Django TypeError?

TypeError:无法将“ int”对象隐式转换为str

TypeError:无法将“ int”对象隐式转换为str

Python:TypeError:无法连接“ str”和“ int”对象

TypeError:无法将int隐式转换为str

TypeError:必须为str,而不是int无法解决

在包含 NAN 的数据帧单元格中提取 int 值并出现错误 TypeError: unorderable types: str() > int()

为什么我会收到“int is not subscriptable”错误消息?

excel + vba + 编译错误 AutoOpenRequiredWorkbook (myFileNameToOpen, myFilePath) 无法弄清楚为什么我会收到此错误

为什么我无法从数据框中获取饼图。TypeError:“ str”和“ int”的实例之间不支持“ <”

我该如何解决“ TypeError:只能将str(而不是“ int”)连接到str”

我收到一个错误,无法将 int* 转换为 int,但我无法弄清楚是什么导致了它

Python TypeError必须为str not int

使用Python的TypeError:str和int

TypeError:无法连接“ str”

为什么我会收到Uncaught TypeError:无法在分配时读取未定义的属性“ 0”?

为什么我会收到 TypeError:无法读取未定义的 react-router-dom 的属性“push”