Reputation: 775
Is it possible to use getattr
/setattr
to access a variable in a class function?
Example below. Say I have a class A, that has two methods, func1
and func2
both
of which define a variable count
of a different type. Is there a way to use
getattr
in func2 to access the local variable count
?
In reality, I have quite
a few variables in func2
(that are also defined differently in func1
) that I want
to loop through using getattr
and I'm looking to shorten up my code a bit by using
a loop through the variable names.
class A(object):
def __init__(self):
pass
def func1(self):
count = {"A": 1, "B":2}
def func2(self):
count = [1, 2]
mean = [10, 20]
for attr in ("count", "mean"):
xattr = getattr(self, attr) ! What do I put in here in place of "self"?
xattr.append(99)
Upvotes: 15
Views: 15331
Reputation: 2520
This has been answered before on Stackoverflow... In short:
import sys
getattr(sys.modules[__name__], attr)
Edit: you can also look up and update the dict returned by globals()
directly, ex. this is roughly equivalent to the getattr()
above:
globals()[attr]
Upvotes: 17
Reputation: 1124548
No, getattr()
and setattr()
only work with attributes on an object. What you are trying to access are local variables instead.
You can use locals()
to access a dictionary of local names:
for name in ("count", "mean"):
value = locals()[name]
value.append(99)
but it'd be better just to name the lists directly, there is no need to go through such trouble here:
for value in (count, mean):
value.append(99)
Upvotes: 21