清单理解级别,Python 3

时间:2019-04-02 13:28:56

标签: python

考虑以下代码:

class MyMegaClass(object):
    excluded_fields = {1, 2}

    all_fields = list(range(10))
    print(excluded_fields)
    valid_fields = [itm for itm in all_fields if itm not in excluded_fields]
cl = MyMegaClass()
print(cl.valid_fields)

此代码在Python 2.7上运行良好。 但是Python 3.7在列表理解的范围内引发了一个异常。它没有看到“ excluded_fields”字段。虽然,“ print(excluded_files)”有效! 仅在列表理解中的“ if”之后,“ excluded_field”不可见。有什么想法吗?

回溯:

Traceback (most recent call last):
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 1, in <module>
class MyMegaClass(object):
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 6, in MyMegaClass
valid_fields = [itm for itm in all_fields if itm > len(excluded_fields)]
File "C:/Users/S2400244/PycharmProjects/enumtest/classfieldtest.py", line 6, in <listcomp>
valid_fields = [itm for itm in all_fields if itm > len(excluded_fields)]
NameError: name 'excluded_fields' is not defined

0 个答案:

没有答案