python对象中的布尔属性

时间:2017-11-15 23:28:08

标签: python

它只需要一个字符串。我希望它是布尔值。 另外self.__isgood = goodornot应该抛出错误,为什么不呢?

class Animal:
    Name = ""
    isgood = None

    def setisgood(self,goodornot):
        self.__isgood = goodornot

    def nameset(self,name):
        self.Name = name


dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:"+dog.isgood)

2 个答案:

答案 0 :(得分:1)

然后将其转换为字符串。

print("Your pet is: {}".format(dog.isgood))

答案 1 :(得分:1)

print("Your pet is:"+dog.isgood)

正在尝试连接布尔值和字符串,这是无法完成的。为此,您需要将dog.isgood转换为字符串

print("Your pet is:" + str(dog.isgood))
像评论中提出的TheoretiCAL一样,或者使用格式

print("Your pet is:{}".format(dog.isgood))
像Ignacio Vazquez-Abrams一样回答,或

print("Your pet is:%s" % dog.isgood)

,或者

print("Your pet is:", dog.isgood)

所有这些示例都将产生以下输出:

Your pet is:False

编辑: 感谢juanpa指出这一点。类上的间距是不正确的,应该引起一个问题(我想我最初假设它只是一个复制粘贴的东西)。

class Animal:
    def __init__(self):
        self.Name = ""
        self.isgood = None

    def setisgood(self,goodornot):
        self.isgood = goodornot

    def nameset(self,name):
        self.Name = name


dog = Animal()
dog.setisgood(False)
dog.nameset("jaang")
print("Your pet is:", dog.isgood)
相关问题