Python错误TypeError:无法连接' str'和' int'对象

时间:2014-11-23 11:30:23

标签: python

我从一本名为Hello World 2nd Edition的书中学习。

在第14章第171页我必须写一个程序。 这就是我写的:

class HotDog:
    def __init__(self):
        self.cooked_level = 0
        self.cooked_string = "Raw"
        self.condiments = []
    def __str__(self):
        msg = "hot dog"
        if len(self.condiments) > 0:
            msg = msg + "with"
        for i in self.condiments:
            msg = msg+i+", "
        msg = msg.strip(", ")
        msg = self.cooked_string + " " + msg +"."
        return msg
    def cook(self, time):
        self.cooked_level=self.cooked_level+time
        if self.cooked_level > 8:
            self.cooked_string = "charcoal"
        elif self.cooked_level > 5:
            self.cooked_string = "Well-done"
        elif self.cooked_level > 3:
            self.cooked_level = "Medium"
        else:
            self.cooked_string = "raw"
    def addCondiemnet(self, condiment):
        self.condiments.append(condiment)

myDog = HotDog()
print myDog
print "Cooking my Hot Dog for 4 minutes...."
myDog.cook(4)
print myDog
print "Cooking hot dog for 3 more Minutes"
myDog.cook(3)
print myDog
print "What happens if I cook it for 10 more minutes?"
myDog.cook(10)
print myDog
print "Now, im going to add some stuff to my hot dog"
myDog.addComdiment("ketchup")
myDog.addComdiment("More ketchup")
myDog.addComdiment("AND More ketchup")
print myDog

如果我运行它,我会收到错误消息:

Traceback (most recent call last):
  File "C:\Users\Jay\Desktop\Python Programs\Chapter 1\AdvancedHOTDOG.py", line 34, in <module>
    myDog.cook(3)
  File "C:\Users\Jay\Desktop\Python Programs\Chapter 1\AdvancedHOTDOG.py", line 16, in cook
    self.cooked_level=self.cooked_level+time
TypeError: cannot concatenate 'str' and 'int' objects

如果您知道问题,请回复。

1 个答案:

答案 0 :(得分:3)

问题在于第22行:

self.cooked_level = "Medium"

您正在为self.cook_level分配一个字符串。

该行应该是:

 self.cooked_string = "Medium"