Source From Here
QuestionIs 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)
HowTo
- import sys
- getattr(sys.modules[__name__], attr)
- globals()[attr]
沒有留言:
張貼留言