finding name of instances created

Steven Bethard steven.bethard at gmail.com
Fri Jan 21 21:43:27 EST 2005


André Roberge wrote:
> Behind the scene, I have something like:
> robot_dict = { 'robot' = CreateRobot( ..., name = 'robot') }
> and have mapped move() to correspond to
> robot_dict['robot'].move()
> (which does lots of stuff behind the scene.)
> 
> I have tested robot_dict[] with more than one robot (each with
> its own unique name)  and am now at the point where I would like
> to have the ability to interpret something like:
> 
> alex = CreateRobot()
> anna = CreateRobot()
> 
> alex.move()
> anna.move()
> 
> etc. Since I want the user to learn Python's syntax, I don't
> want to require him/her to write
> alex = CreateRobot(name = 'alex')
> to then be able to do
> alex.move()

How do you get the commands from the user?  Maybe you can preprocess the 
user code?

py> class Robot(object):
...     def __init__(self, name):
...         self.name = name
...     def move(self):
...         print "robot %r moved" % self.name
...
py> user_code = """\
... alex = Robot()
... anna = Robot()
... alex.move()
... anna.move()"""
py> new_user_code =  re.sub(r'(\w+)\s+=\s+Robot\(\)',
...                         r'\1 = Robot(name="\1")',
...                         user_code)
py> print new_user_code
alex = Robot(name="alex")
anna = Robot(name="anna")
alex.move()
anna.move()
py> exec new_user_code
robot 'alex' moved
robot 'anna' moved

Steve



More information about the Python-list mailing list