类方法不返回任何内容

2024-09-29 19:22:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我打电话(接通)有问题吗我班上的方法

class dag(object):

    def __init__(self,temp):
        self.name = temp[3]
        self.l_o_t = temp

    def __str__(self):

        print ("The hottest temperature was:",self.l_o_t[0])
        print ("The coolest temperature was:",self.l_o_t[1])
        print ("The average temperature was:",self.l_o_t[2])

    def returnmax(self):

        return self.l_o_t[0]
    def returnmin(self):
        return self.l_o_t[1]
    def returnavg(self):
        return self.l_o_t[2]


def main():
    temp = dag(list_of_temperatures)
    temp.returnmax()
    temp.returnmin()
    temp.returnavg()
    temp.__str__()

当试图打印出returnmaxreturnminreturnavg返回的值时,主程序不打印任何内容。只有打印语句,如str方法似乎可以工作,为什么?在


Tags: the方法selfreturndeftempclassdag
2条回答

str(obj)将调用def __str__(self)函数,因此str函数需要返回值,而不是打印值

当函数返回值但忘记打印时,将看不到它

它和贝壳不一样

class dag(object):

    def __init__(self,temp):
        self.name = temp[3]
        self.l_o_t = temp

    def __str__(self):
        a = "The hottest temperature was:%s"%self.l_o_t[0]
        b = "The coolest temperature was:%s"%self.l_o_t[1]
        c = "The average temperature was:%s"%self.l_o_t[2]
        return '\n'.join([a,b,c])

    def returnmax(self):
        return self.l_o_t[0]
    def returnmin(self):
        return self.l_o_t[1]
    def returnavg(self):
        return self.l_o_t[2]


def main():
    temp = dag([27,19,23,'DAG'])
    print(temp.returnmax())
    print(temp.returnmin())
    print(temp.returnavg())
    print(temp) # print will call str, that is __str__


if __name__ == '__main__':
    main()

Python交互式解释器为您回显所有内容,因为它是一个交互式调试器,但是在Python程序中,您需要显式地打印值。在

添加print()调用以显示返回值:

temp = dag(list_of_temperatures)
print(temp.returnmax())
print(temp.returnmin())
print(temp.returnavg())

通常,__str__方法将返回一个字符串值,而不是在方法中使用print()

^{pr2}$

然后使用print(),它将对该值调用str(),后者又调用__str__()方法:

print(temp)

相关问题 更多 >

    热门问题