On Feb 24, 5:52 am, Nomen Nescio <[email protected]> wrote:
> Hello,
>
> Can someone help me understand what is wrong with this example?
>
> class T:
> A = range(2)
> B = range(4)
> s = sum(i*j for i in A for j in B)
>
> It produces the exception:
>
> <type 'exceptions.NameError'>: global name 'j' is not defined
>
> The exception above is especially confusing since the following similar
> example (I just replaced the generator by an explicit array) works:
>
> class T:
> A = range(2)
> B = range(4)
> s = sum([(i*j) for i in A for j in B])
>
> (BTW, the class scope declarations are intentional).
>
> Thanks, Leo.
The best way to mimic the same behavior, while getting around the
scoping issues, would be as follows:
class T:
A = range(2)
B = range(4)
@property
def s(self):
return sum(i*j for i in self.A for j in self.B)
T().s will now return 6
--
http://mail.python.org/mailman/listinfo/python-list