在 python 3.x 中的方法内打印

Printing inside a method in python 3.x

我想在方法中打印一些东西。但是下面的代码没有任何作用。但是如果我 return 我能够在 class 之外打印它的值。为什么会这样?任何指导都会很棒!

我的代码:

import pytest


class Test:

    def __init__(self, val_1, val_2):
        self.val_1 = val_1
        self.val_2 = val_2
        self.sum = 0
        self.mul = 0


    def sum_mul(self):
        self.sum = self.val_1 + self.val_2
        self.mul = self.val_1 * self.val_2

    def ret_val(self):
        return self.sum, self.mul 

    def test_exception(self,exception):
        raise exception
        return str(exception)

class Assert_Values:

    def __init__(self, number, val_1, val_2, exception):
        self.number = number
        self.val_1 = val_1
        self.val_2 = val_2
        self.exception = exception
        self.test_obj = Test(self.val_1, self.val_2)

    def execute_test(self):
        if self.number == 1:
            self.test_obj.sum_mul()
            self.val = self.test_obj.ret_val()
            assert self.val == (self.val_1 + self.val_2, self.val_1 * self.val_2)
            print (self.val)

        elif self.number == 2:
            with pytest.raises(self.exception):
                self.exception_val = self.test_obj.test_exception(self.exception)
                print (self.exception_val)
        else:
            print ("! Number not valid %d please enter another number" % (self.number))

assert_values = Assert_Values(2,4,5,ValueError)
assert_values.execute_test()

Pytest captures stdoutprint() 写入 stdout,如果测试失败,您将 看到输出。

如果您想看到 stdout 输出,请使用 -s 标志:

py.test -s