metric
is just a local variable, and it is not a reference to the attribute. When you call a function or a method, python passes in the referenced object. That means the value referenced by a.num1
or a.num2
is passed in, not an attribute. In your example, metric
is 0
in both cases because the result of the expressions a.num1
and a.num2
is both 0
.
If you wanted to tell a method what attribute to assign to, use setattr()
and pass in a string:
def selfexp(self, n, metric):
result = n ** n
setattr(self, metric, result)
print getattr(self, metric)
and:
a.selfexp(2, 'num1')
I used the getattr()
function to read the same named attribute again as well.