python对象的麻烦

时间:2014-03-23 18:06:45

标签: python class object

class dog(object):
    def __init__(self, name = "", breed = "", age = "", weight = "", colour = ""):
        self.name = name
        self.breed = breed
        self.age = age
        self.weight = weight
        self.colour = colour
    def printDog(self):
        print("Name: " + self.name)
        print("Breed: " + self.breed)
        print("Age: " + self.age)
        print("Weight: " + self.weight)
        print("Colour: " + self.colour)


def main():
    chester = dog()
    lola = dog()

if __name__ == "__main__":
     main()

所以在dog课程中。我让你能够创建自己的狗实例并赋予它属性,而且我还有一个函数可以让你打印关于你的狗实例的信息。

但是当我在dog中制作main时,我无法在shell中调用它。这很奇怪帮助我。

1 个答案:

答案 0 :(得分:2)

我认为你的意思是像下面那样实例化狗

chester = dog(name = "chester", breed = "pomerian", age = "2 years", weight = "70 kgs", colour = "white")

然后像

一样查看它们
chester.printDog()

您正在main函数中实例化狗,因此在该函数之外它们将无法使用。

此外,就目前而言,您的所有输入都必须是字符串,否则如果您为年龄或体重属性提供整数值,您将获得TypeError: cannot concatenate 'str' and 'int' objects