Question

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.

Was it helpful?

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.

OTHER TIPS

I think this is what you're after, but not totally sure...

print getattr(self, s)

You can also use it to specify what to return if it doesn't exist. See the getattr docs

print getattr(self, s, 'default value')
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top