Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use of python getattr/setattr for current function

Tags:

python

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)
like image 621
user3014653 Avatar asked Nov 20 '13 19:11

user3014653


People also ask

What is Setattr () and Getattr () used for?

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.

What is the usage of Setattr () function?

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.

What is Getattr () used for in Python?

The getattr() function returns the value of the specified attribute from the specified object.

How many arguments Getattr () function receives in Python?

Python getattr() If neither of these exists, an AttributeError is thrown. The getattr() function accepts 2 or 3 values as its parameter.


2 Answers

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]
like image 119
Thomas Guyot-Sionnest Avatar answered Sep 19 '22 22:09

Thomas Guyot-Sionnest


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)
like image 38
Martijn Pieters Avatar answered Sep 20 '22 22:09

Martijn Pieters