1

I have class A:

class A:
    a = 2
    b = 3
    c = 4

And I added to it methods for getting each member (get_a, get_b, get_c) by

for attrib in ('a', 'b', 'c'):
    f = lambda self: getattr(self, attrib)
    setattr(A, 'get_'+attrib, f)

Surprisingly calling each method on created instance:

a = A()
print(a.get_a())
print(a.get_b())
print(a.get_c())

Results in

4
4
4

Not in as I expected

2
3
4

I figured out that expanding the loop to 3 uses of setattr do the thing, but why? Why rolling up 3 uses of setattr changes anything?

Yuras
  • 484
  • 1
  • 3
  • 11

0 Answers0