# Works class Test: a = [1, 2, 3] b = [1, 2, 3] c = [i for i in a] # Raises NameError: name 'b' is not defined class Test: a = [1, 2, 3] b = [1, 2, 3] c = [i*j for i in a for j in b]
-
Prikaži ovu nit
-
Turns out the reason for this is that the outermost iterable of a comprehension is executed in the surrounding scope.https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition …
1 reply 0 proslijeđenih tweetova 6 korisnika označava da im se sviđaPrikaži ovu nit -
Just when I thought I'd got a hold on Python's scoping rules I discover another weird corner case. I think the moral of the story is to minimize the amount of code written on a class body (code in class bodies is bad for other reasons too).
1 proslijeđeni tweet 6 korisnika označava da im se sviđaPrikaži ovu nit -
Showed this at work today and I didn't realize more people are unaware that even class A: x = 1 a = [x for i in range(9)] gives a NameError. It's for the same reason that this does: class A: x = 1 def f(self): print(x) A().f()
1 reply 0 proslijeđenih tweetova 2 korisnika označavaju da im se sviđaPrikaži ovu nit
Code on class bodies doesn't act like code at a module level or in a function body. Nested local scopes like can't see class variables. This includes list comprehensions because they run in their own scope (just like they were a separate function).
Čini se da učitavanje traje već neko vrijeme.
Twitter je možda preopterećen ili ima kratkotrajnih poteškoća u radu. Pokušajte ponovno ili potražite dodatne informacije u odjeljku Status Twittera.