Accessing class variables from a list comprehension in the class definition

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

    This is a bug in Python. Comprehensions are advertised as being equivalent to for loops, but this is not true in classes. At least up to Python 3.6.6, in a comprehension used in a class, only one variable from outside the comprehension is accessible inside the comprehension, and it must be used as the outermost iterator. In a function, this scope limitation does not apply.

    To illustrate why this is a bug, let's return to the original example. This fails:

    class Foo:
        x = 5
        y = [x for i in range(1)]
    

    But this works:

    def Foo():
        x = 5
        y = [x for i in range(1)]
    

    The limitation is stated at the end of this section in the reference guide.

提交回复
热议问题