如何在 Python 上设置 namedTuple 中的字段值?

How to set the field values in namedTuple on Python?

在我的 pytest (python 3.7.4) 中,我有定义和设置 namedtuple 字段值的测试方法。但是,尽管我在我的代码中设置了值,但我实际上并没有看到任何值设置到字段中。

def test_TapVisaCardOnTheReader(Process):
    ResponseResults = namedtuple('ResponseResults',['STATUS', 'ISO8583', 'TOKEN', 'ICC_PUBLIC_KEY'])
    ResponseResults('01', True, True, True)
    TapResponseResults=Process.TappingPaymentCardOntheReader(' Visa-Card ')
    assert ((ResponseResults.STATUS == TapResponseResults.STATUS) and (
            ResponseResults.ISO8583 == TapResponseResults.ISO8583) and (
                    ResponseResults.TOKEN == TapResponseResults.TOKEN) and (
                    ResponseResults.ICC_PUBLIC_KEY == TapResponseResults.ICC_PUBLIC_KEY))

请检查以下调试输出 window,其中我没有看到任何已设置的值。

另外我还有一个关于 namedtuple 字段比较的问题,在我的代码中我不得不比较 namedtuple 的每个字段,而是有什么方法可以比较 namedtuple 的所有字段一次。

在这部分代码中,您创建了 ResponseResults 对象而不保存它:

ResponseResults = namedtuple('ResponseResults',['STATUS', 'ISO8583', 'TOKEN', 'ICC_PUBLIC_KEY'])
ResponseResults('01', True, True, True)

你真正想要的是:

ResponseResults = namedtuple('ResponseResults',['STATUS', 'ISO8583', 'TOKEN', 'ICC_PUBLIC_KEY'])
response_results = ResponseResults('01', True, True, True)
# continue with response_results...

编辑:关于你的第二个问题:如果你想直接比较两个命名元组的所有字段,你可以使用 == 运算符:

from collections import namedtuple

ResponseResults = namedtuple('ResponseResults',['STATUS', 'ISO8583', 'TOKEN', 'ICC_PUBLIC_KEY'])
response_results = ResponseResults('01', True, True, True)
response_results_2 = ResponseResults('01', True, True, True)
response_results_3 = ResponseResults('01', True, True, False)

response_results == response_results_2 # this is True
response_results == response_results_3 # this is False