How come a returned string can be interpreted as a function in python? -


I learn the dragon by hard way and in the code snippet as I like below I've come. But I did not understand what is behind it, a function basically gives a string which is the function of the same name in the class. And it can call the function properly.

  Exit import from the class game (object): def __init __ (auto, start): self. Start = RF game (self): next = self.start while correct: print "\ n --------" room = getattr (self, next) next = rooms () def a1 (self): print " You are redirecting to A2, you are redirecting to A2, "Return 'A2' Def A2 (Self): Print" You are in A2, Returns from Death Def Def Death (Self) '0) a_game = Game ('a1') a_game.play ()    

What do you see Getattr () is the result of builtin. Python is a high level language and what is more, an explanation Since all objects in the dragon are originally made in the form of hash-tables in memory, therefore Python has no large system.

This means that Python runtime and there is a way to do this getattr () builtin receives value of the getattr builtin member in the first argument, which Name gets it as string The second argument is similar to getattr (x, "y") basically xy Is it Kin getattr also allows a safe approach where a default value can be given if a member is not actually present: getattr (x, "y", "such a member No ") . If there is no member of x then y then x.y will be the cause of an AttributeError . On the other hand, gettattr (x, "y", "no such member is not there") "no such member" will return the string and no exceptions will be raised.

In your case, the methods are placed in the next variable as strings and getattr () builtin rooms Is kept in The cell () is then applied and the names of the next methods are stored back and in the next . In Loop until Exit (0) applies game.death () . There is also a look at

setattr () and hatter ()

Comments

Popular posts from this blog

mysql - BLOB/TEXT column 'value' used in key specification without a key length -

c# - Using Vici cool Storage with monodroid -

python - referencing a variable in another function? -