类方法不返回任何内容

时间:2014-02-26 13:21:55

标签: python python-3.2

我在调用(访问?)类中的方法时遇到问题

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 方法似乎有效,为什么会这样?

2 个答案:

答案 0 :(得分:4)

Python交互式解释器为您提供了一切,因为它是一个交互式调试器,但在Python程序中,您需要显式打印值。

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

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

通常情况下,__str__方法会在方法中返回字符串值,使用print()

def __str__(self):
    value = (
        'The hottest temperature was: {0.l_o_t[0]}\n'
        'The coolest temperature was: {0.l_o_t[1]}\n'
        'The average temperature was: {0.l_o_t[2]}\n'
    ).format(self)
    return value

然后您使用print(),这会在值上调用str(),然后调用__str__()方法:

print(temp)

答案 1 :(得分:1)

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

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

它与shell

不同
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()
相关问题