using getattr/setattr for local variables in a member function

MRAB python at mrabarnett.plus.com
Thu Nov 21 19:52:21 EST 2013


On 21/11/2013 23:12, Catherine M Moroney wrote:
> Hello,
>
> If I have a class that has some member functions, and all the functions
> define a local variable of the same name (but different type), is there
> some way to use getattr/setattr to access the local variables specific
> to a given function?
>
> Obviously there's no need to do this for the small test case below,
> but I'm working on a bigger code where being able to loop through
> variables that are local to func2 would come in handy.
>
> For example:
>
> class A(object):
>      def __init__(self):
> 	pass
>
>      def func1(self):
> 	a = {"A": 1}
> 	b = {"B": 2}
>
>      def func2(self):
>           a = [1]
> 	b = [2]
>
> 	for attr in ("a", "b"):
> 	   var = getattr(self, attr)  ! What do I put in place of self
> 	   var.append(100)            ! to access vars "a" and "b" that
>                                         ! are local to this function?
>
You can get the local names of a function using locals():

class A(object):
     def __init__(self):
         pass

     def func1(self):
         a = {"A": 1}
         b = {"B": 2}

     def func2(self):
         a = [1]
         b = [2]

         for name in ("a", "b"):
             var = locals()[name]
             var.append(100)

BTW, in Python they're called "methods". (C++ calls them "member
functions", but Python isn't C++!)




More information about the Python-list mailing list