Dynamically reference variable in object
Sorry, subject was wrong. Please see below: On Wednesday, 26 March 2014 11:43:49 UTC, Ben Collier wrote: Hi all, I know that I can dynamically reference a variable with locals()[i], for instance, but I'd like to know how to do this with a variable in an object. If I have an object called device, with variables called attr1, attr2 .. attr50, how could I dynamically reference these? It's fairly academic, but I'd like to avoid code duplication. Thanks, Ben -- https://mail.python.org/mailman/listinfo/python-list
Re: Dynamically reference variable in object
On Mar 26, 2014 5:48 AM, Ben Collier bmcoll...@gmail.com wrote: Sorry, subject was wrong. Please see below: On Wednesday, 26 March 2014 11:43:49 UTC, Ben Collier wrote: Hi all, I know that I can dynamically reference a variable with locals()[i], for instance, but I'd like to know how to do this with a variable in an object. If I have an object called device, with variables called attr1, attr2 .. attr50, how could I dynamically reference these? It's fairly academic, but I'd like to avoid code duplication. You want to access object attributes, not variables. You can do this using the functions getattr and setattr like so: class Foo(object): pass ... obj = Foo() setattr(obj, x, 42) print(obj.x) 42 print(getattr(obj, x)) 42 -- https://mail.python.org/mailman/listinfo/python-list
Re: Dynamically reference variable in object
On Wed, 26 Mar 2014 15:19:03 -0600, Ian Kelly wrote: You want to access object attributes, not variables. In fairness to the OP, the terminology instance variables meaning attributes or members of an instance is (sadly, in my opinion) common in some other languages, such as Java, and occasionally creeps into even the Python docs. I've often ranted about this, and won't repeat it now, only point out that the preferred and most common terminology in Python circles is attribute, or instance attribute if you need to distinguish it from class attribute. -- Steven D'Aprano http://import-that.dreamwidth.org/ -- https://mail.python.org/mailman/listinfo/python-list