Search code examples
pythonstringclassselfhasattr

In Python, how do I get a variable via a string representation of the name of the variable?


I'm using Python 2.7.

Take, for example, the following code:

class Apple:
    def __init__(self, n):
        self.n = n
    def printVariable(self, s): # print variable named s
        if hasattr(self, s):
            print ...

What would I replace ... with to print self.'s'. For example, if I called printVariable('n'), what would I put in place of ... to print n?

Of course, self.s would not work because first of all there is no attribute self.s, but more importantly, that's printing a different variable, not the variable self.'s' I want to print the variable whose name is represented by the string s that is passed to the method.

I'm sorry about the inherently confusing nature of self.s and self.'s' and s in this question.


Solution

  • If hasattr(self,s), is sufficient to your needs, then you want getattr() :

    if hasattr(self, s):
        print getattr(self, s)
    

    In fact, you may be able to skip the hasattr altogether, depending upon your precise requirement. getattr() takes a default value to return if the attribute is missing:

    print gettattr(self, s, 'No such attribute: '+s)
    

    If you want to find variables outside of the current object (say, in local scope or global scope, or in another object), try one of these:

    locals()[s]
    globals()[s]
    getattr(other_object, s)
    

    Note: using locals(), globals(), and to a lesser extent, hasattr(self,s), outside of a few limited cases, is a code smell. It almost very likely means that your design is flawed.