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)
Python setattr() and getattr() goes hand-in-hand. As we have already seen what getattr() does; The setattr() function is used to assign a new value to an object/instance attribute.
Python setattr() function is used to assign a new value to the attribute of an object/instance. Setattr in python sets a new specified value argument to the specified attribute name of a class/function's defined object.
The getattr() function returns the value of the specified attribute from the specified object.
Python getattr() If neither of these exists, an AttributeError is thrown. The getattr() function accepts 2 or 3 values as its parameter.
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]
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With