Python Macros

Carlos Ribeiro carribeiro at gmail.com
Tue Oct 5 08:45:05 EDT 2004


On Mon, 04 Oct 2004 23:19:05 -0400, Arich Chanachai
<macrocosm at fastmail.fm> wrote:
> Code fragment:
> 
> [Dog fetch:cat]  ---> Dog doesn't know how to fetch cat  --->  Dog
> passes message to human and essentially makes the following call --->
> [Human fetch:cat]  ----> and so forth

Other posters have already pointet out to you some alternatives. If
Dog and Human are both classes, there are many things you can do.

-- If the classes are related in a hierarchy, then the descendent
class will call the superclass method (as in any sane OOP language,
mind you);

-- By providing your own __getattr__ function, you can put yourself in
the position to decide who must fetch the cat. In this case, a code
like this (untested) will do it:

class Human:
    def fetch(self, thing):
        print "Asked to fetch '%s'" % thing
class Dog:
    def __init__(self, owner=None):
        self.owner = owner
    def __getattr__(self, attrname):
        # self.__dict__ contains the local dict of Dog
        message = getattr(self.__dict__, attrname, None)
        if message:
            # message is really a method, anyway...
            return message
        else:
            # asks the owner if it supports the message
            return getattr(self. owner, attrname)

>>> joe = Human()
>>> dog = Dog(joe)
>>> dog.fetch('cat')
Asked to fetch 'cat'

The problem with the code above is that joe.fetch() does not know that
the message 'fetch' was deferred from the dog (the value of self is
bound to the 'joe' instance when the object is created). Of course,
there is a lot of things that you can do to solve this problem; for
example, the 'ownership' relationship could be implemented
bidirectionally, so the owner would know that his dog could be asking
him a favour. Another idea is to use MixIns -- classes that than be
added to another class to provide some functionality, but that leads
to a different type of solution architecturally speaking.

-- 
Carlos Ribeiro
Consultoria em Projetos
blog: http://rascunhosrotos.blogspot.com
blog: http://pythonnotes.blogspot.com
mail: carribeiro at gmail.com
mail: carribeiro at yahoo.com



More information about the Python-list mailing list