tags:

views:

264

answers:

2

In PHP I can do the following:

$myVar = 'name';

print $myClass->$myVar;
// Identical to $myClass->name

I wish to do this in Python but can't find out how

+16  A: 

In python, it's the getattr built-in function.

class Something( object ):
    def __init__( self ):
        self.a= 2
        self.b= 3

x= Something()
getattr( x, 'a' )
getattr( x, 'b' )
S.Lott
+5  A: 

You'll want to use the getattr builtin function.

myvar = 'name'

//both should produce the same results
value = obj.name
value = getattr(obj, myvar)
Alan Storm