Accessing class variables from a list comprehension in the class definition

前端 未结 5 875
挽巷
挽巷 2020-11-21 04:25

How do you access other class variables from a list comprehension within the class definition? The following works in Python 2 but fails in Python 3:

class          


        
5条回答
  •  灰色年华
    2020-11-21 05:12

    Since the outermost iterator is evaluated in the surrounding scope we can use zip together with itertools.repeat to carry the dependencies over to the comprehension's scope:

    import itertools as it
    
    class Foo:
        x = 5
        y = [j for i, j in zip(range(3), it.repeat(x))]
    

    One can also use nested for loops in the comprehension and include the dependencies in the outermost iterable:

    class Foo:
        x = 5
        y = [j for j in (x,) for i in range(3)]
    

    For the specific example of the OP:

    from collections import namedtuple
    import itertools as it
    
    class StateDatabase:
        State = namedtuple('State', ['name', 'capital'])
        db = [State(*args) for State, args in zip(it.repeat(State), [
            ['Alabama', 'Montgomery'],
            ['Alaska', 'Juneau'],
            # ...
        ])]
    

提交回复
热议问题