I have the following piece of code:
d = dict(q='q', w='w', e='e')
class A(object):
pass
for o in d.items():
print o
def _method(self):
return o[0]
setattr(A, o[1], _method)
a = A()
print a.q()
print a.w()
print a.e()
Output:
('q', 'q')
('e', 'e')
('w', 'w')
w
w
w
Desired output:
('q', 'q')
('e', 'e')
('w', 'w')
q
w
e
For the sake of simplicity, I have simplified the dictionary d and the class A. In reality, they are complex. Basically, I am trying to add methods dynamically to my class A since they are all pretty much similar and I don't want to copy paste code for each method. But the problem is all the dynamically assigned methods are equivalent to the last value of _method
.
How do I get the desired output?
Thanks in advance!