gagsl-py at yahoo.com.ar
Tue Oct 10 04:49:50 CEST 2006
At Monday 9/10/2006 21:15, Liquid Snake wrote:
>Hello :). Some days ago i went to a seminar
>about Metaprograming and Reflection.
>I was a little famirialized with the subject,
>and wanted to explore it further.
>The seminar was great, but the point is that
>every example was programmed in smalltalk.
>I know smalltalk, and never have much use for
>the doesNotUnderstand method until the guys at
>the conference open my eyes with some examples.
>Altough i have applied concepts of reflection in
>python many times, i think i't will be nice to
>have a magic method that works like doesNotUnderstand for some purposes.
>The reason i'm writing is because i want to know
>if such method already exists... or maybe... if
>you think having one it's a good/possible idea.
>Right now... im thinkng i really can emulate
>that behavior using Exceptions..., and i really
>think that's what SmallTalk kind of do
>under-the-hood (dont flame me if i'm terribly worng plz).
>But i still want to know if theres a method like
>__insertMethodNameHere__ that does it for me...
>or if you think it's a nice thing to have...
I'm not a Smalltalk guru, but I think
Object>>doesNotUnderstand is called whenever the
object receives an unknown message.
In Python, you have __getattr__ which is called
after unsuccessful looking for an attribute in
the usual places ("attribute" may be a method name too).
A typical example is a proxy: an object which
forwards method calls to another, "real" one. In
your seminar I guess they talked about the
difficulty to do a "generic" proxy using other
languages like C++ (or even Java). In Python it's easy using __getattr__:
def __init__(self, realObject):
self.__dict__['realObject'] = realObject
def __getattr__(self, name):
return getattr(self.realObject, name)
def __setattr__(self, name, value):
return setattr(self.realObject, name, value)
o = some_object()
p = Proxy(o)
p.method(1,2,3) finally calls o.method(1,2,3)
p acts like o: it has the same attributes and so.
Of course __getattr__ may do a lot more: it can
forward the request using xmlrpc to another
server, by example, or whatever you want.
If you look at the Python Cookbook surely you´ll find several examples.
Preguntá. Respondé. Descubrí.
Todo lo que querías saber, y lo que ni imaginabas,
está en Yahoo! Respuestas (Beta).
More information about the Python-list