Accessing class variables from a list comprehension in the class definition

前端 未结 5 888
挽巷
挽巷 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:11

    In my opinion it is a flaw in Python 3. I hope they change it.

    Old Way (works in 2.7, throws NameError: name 'x' is not defined in 3+):

    class A:
        x = 4
        y = [x+i for i in range(1)]
    

    NOTE: simply scoping it with A.x would not solve it

    New Way (works in 3+):

    class A:
        x = 4
        y = (lambda x=x: [x+i for i in range(1)])()
    

    Because the syntax is so ugly I just initialize all my class variables in the constructor typically

提交回复
热议问题