Suggesting for overloading the assign operator

Michele Simionato mis6 at pitt.edu
Thu Jul 3 11:32:28 EDT 2003


rimbalaya at yahoo.com (Rim) wrote in message news:<6f03c4a5.0307022119.2b0a4bc1 at posting.google.com>...
> Everyone! Thanks a lot for the insightful and enlightening discussion.
> 
> I think the suggestion to solve the problem by using the __setattr__
> special method will not work because it intercepts attribute
> assignment of the form "self.attr = somthing", and not what I want,
> which is "name = something".
> 
> John suggested to look at properties, this is the closest I can get to
> the
> behavior I am looking for, but from my understanding, that will let me
> intercept "name.value = something" instead of intercepting "name =
> something".
> 
> Thank you very much everyone.
> - Rim

Okay, you asked for it ;)

class MetaTrick(type):
    def __init__(cls,name,bases,dic):
        super(MetaTrick,cls).__init__(name,bases,dic)
        for (k,v) in dic.iteritems():
            if not k.endswith("__"): setattr(cls,k,v)
    def __setattr__(cls,k,v):
        print "Intercepting %s = %s" % (k,v)
        super(MetaTrick,cls).__setattr__(k,v)

class C:
    __metaclass__=MetaTrick
    name='something'

This gives the output "Intercepting name = something".

I show you this snippet hoping you will not use it! 

nothing-is-impossible-with-metaclasses-ly,

                                 Michele




More information about the Python-list mailing list