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.
If
hasattr(self,s), is sufficient to your needs, then you wantgetattr():In fact, you may be able to skip the
hasattraltogether, depending upon your precise requirement.getattr()takes a default value to return if the attribute is missing: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:
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.