I cannot understand why I cannot reference the integer member of the nested class in the lambda. The following code demonstrates the failure. The same reference is used in the print prior to the reduce command with no issue.
Is there some subtlety I'm missing?
from functools import reduce
class B :
def __init__(self, n) :
self.length = n
class A :
def __init__(self, n) :
self.b = B(n)
myList = [A(1), A(5), A(7)]
print( myList[0].b.length )
print( reduce(lambda a, b : a.b.length + b.b.length, myList) )
I was expecting the lambda in the reduce to add the numbers contained in the listed class. I searched but could find the terminology that would yield an explanation to the problem I am experiencing. The output below shows the error. Any help is appreciated.
1
Traceback (most recent call last):
File "main.py", line 20, in <module>
print( reduce(lambda a, b : a.b.length + b.b.length, myList) )
File "main.py", line 20, in <lambda>
print( reduce(lambda a, b : a.b.length + b.b.length, myList) )
AttributeError: 'int' object has no attribute 'b'