Amazing Python 2: "exec/eval/repr"

1. exec:

      Executing command from string.

class PlayerBase():  
    player_name = None    
    def talk(self):
        print self.player_name, ": It takes five."
                
class Kobe(PlayerBase):
    def __init__(self):
        self.player_name = "Kobe."
        
class TMac(PlayerBase):
    def __init__(self):
        self.player_name = "TMac"

input_name = "TMac"
cmd = "player = " + input_name + "()"
exec(cmd)
player.talk()

Output:

TMac : It takes five.

With "exec", objects of different class types can be created directly from strings without "switch-case"!

(In this way, do we still need to use the design pattern of "Simple Factory"?)

 

2. eval:

       Calculating value from string.

>>> eval( ' 2 * 3 ' )
6
 

3. repr:

      Acquiring string from value.

>>> dict = { "First" : 1, "Second" : 2 }
>>> string = repr(dict)
>>> string
"{'Second': 2, 'First': 1}"
>>> string[17:]
"rst': 1}"

 

4. eval & repr:

    Converting between value and string, which is greatly suitable for transmission of high-level data structs (e.g., a dictionary) over socket!

>>> dict = { "First" : 1, "Second" : 2 }
>>> repr(dict)
"{'Second': 2, 'First': 1}"
>>> eval(repr(dict))
{'Second': 2, 'First': 1}
>>> eval(repr(dict)) == dict
True

 

See more at Chapter 15, 简明 Python 教程 .

你可能感兴趣的:(Python)