Python equivalent to $ this & # 8594; $ varName

In PHP, I can do the following:

$myVar = 'name';

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

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

+3
source share
2 answers

In python, this is a built-in getattr function.

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

x= Something()
getattr( x, 'a' )
getattr( x, 'b' )
+16
source

You want to use the built-in getattr function.

myvar = 'name'

//both should produce the same results
value = obj.name
value = getattr(obj, myvar)
+5
source

Source: https://habr.com/ru/post/1702873/


All Articles