# 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]
-
-
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()
Prikaž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).
Prikaži ovu nit
Kraj razgovora
Novi razgovor -
-
-
Haha, I also didn't know about this. Class bodies feel very strange in general, but this is another level of weird. It starts to make a bit of sense if you think of comprehensions as functions (I think some of the code is shared), but still...
-
It's like a function where the outermost interable is the default of a keyword argument.
- Još 1 odgovor
Novi razgovor -
Č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.