Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #60185
| Date | 2013-11-22 00:52 +0000 |
|---|---|
| From | MRAB <python@mrabarnett.plus.com> |
| Subject | Re: using getattr/setattr for local variables in a member function |
| References | <l6m40a$9vd$1@news.jpl.nasa.gov> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.3021.1385081545.18130.python-list@python.org> (permalink) |
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++!)
Back to comp.lang.python | Previous | Next — Previous in thread | Next in thread | Find similar | Unroll thread
using getattr/setattr for local variables in a member function Catherine M Moroney <Catherine.M.Moroney@jpl.nasa.gov> - 2013-11-21 15:12 -0800 Re: using getattr/setattr for local variables in a member function MRAB <python@mrabarnett.plus.com> - 2013-11-22 00:52 +0000 Re: using getattr/setattr for local variables in a member function Ned Batchelder <ned@nedbatchelder.com> - 2013-11-21 17:58 -0800 Re: using getattr/setattr for local variables in a member function Dave Angel <davea@davea.name> - 2013-11-21 21:02 -0500 Re: using getattr/setattr for local variables in a member function Ethan Furman <ethan@stoneleaf.us> - 2013-11-21 19:18 -0800 Re: using getattr/setattr for local variables in a member function Gregory Ewing <greg.ewing@canterbury.ac.nz> - 2013-11-22 17:07 +1300
csiph-web