Saturday, August 13, 2011

So I have to concede a point about python.

I have heard and seen before several people make the case that in a more "powerful" language design patterns mostly disappear, and that use of design patterns show that the language is lacking. I have seen this pop up from paul graham(http://www.paulgraham.com/icad.html) or I think I saw a video from on of the google go guys putting forth the same idea.

For the most part I always thought that while there might be some truth it is mostly a conceit and favoritism for one's favorite language. Well now is that part where I swallow my pride and say that just isn't true.(Not really surprising most of my ideas eventually turn out wrong. :))

So as mentioned before I am hoping to play with the class at ai-class.com, Well I ordered the book and I was cruising through some of the code examples(python, I am sure lisp is more enlightening but my mind is not ready to be blown that much, plus I don't have too much time to pick up another language just right now) and I saw the neatest bit of code.

It was in some of the chapter 2 examples http://aima-python.googlecode.com/svn/trunk/agents.py

I shrunk down the code and modified to look and play with the feature that I thought was cool. Now keep in mind you crazy pythonistas I am not a long term python user so this is probably run of the mill to you. any way

class Agent ():

    def __init__(self):
        self.alive = True
        self.bump = False

    def make_agent_program (self):
       print ('Unmodified agent')

    def can_grab (self, obj):
        """Returns True if this agent can grab this object.
        Override for appropriate subclasses of Agent and Object."""
        return False
    
def TraceAgent(agent):
    """Wrap the agent's program to print its input and output. This will let
    you see what the agent is doing in the environment."""
    old_program = agent.make_agent_program
    def make_agent_program():
       print ('modifiesds'  )
       old_program()
    agent.make_agent_program = make_agent_program
    return agent

funk = Agent()
funk.make_agent_program() # prints 'Unmodified agent'
TraceAgent(funk)
funk.make_agent_program()  # prints 'modifiesds\n' + 'Unmodified agent'


Ok so it is kinda like a decorator pattern or something similar but you did it without modifying the original at all!!! I mean I have done a couple of similar things in c++ but you either have to do it with inheritance(and create the object as the child object to begin with) or add a visitor method or something to make it extensible. It is much more painful than doing this. All I can say is download python fire it up and type "import antigravity". Python will even let you fly!!! ;)

No comments:

Post a Comment