Can __iter__ be used as a classmethod?

Michele Simionato mis6 at pitt.edu
Tue Mar 11 21:03:46 CET 2003


Thomas Heller <theller at python.net> wrote in message news:<bs0i3rvc.fsf at python.net>..
> 
> Maybe 'classmethod' is as weird as what some people aks for in this
> forum (and they are overly happy if I point out that it is indeed
> possible, while the 'right' answer would probably be 'you don't want to
> desing your program in this way'): Have a method that binds to the class
> if called from the class, and binds to the instance if called from an
> instance.
> 
> > 
> > > And _having_ to write a custom metaclass as the
> > > only way to get classmethods would be somewhat of an overkill.
> 
> While Guido doesn't like this notation, I actually find it nice:
> 
> class MyClass(object):
> 
>     class __metaclass__(type):
> 
>         def my_class_methods(cls):
>             .....
> 
>     def my_normal_method(self):
>         ....
> 
> (Donald Beaudry had a similar notation in his objectmodule.c, which
> also provided class methods).
> 
> Thomas

I have used that trick few days ago to define Frozen classes:

def frozen(self,name,value):
    if hasattr(self,name):
        object.__setattr__(self,name,value) # standard __setattr__
    else:
        raise AttributeError("You cannot add attributes to %s" % self)

class Frozen(object):
    """Subclasses of Frozen are frozen, i.e. it is impossible to add
     new attributes to them and their instances, except via inheritance"""
    __setattr__ = frozen
    class __metaclass__(type):
        __setattr__ = frozen

This kills Python dynamism. Also, it become impossible to use the
self.var=something idiom, and one is forced to write code as in a 
static compiled language. It protects your code against run-time
modifications (unless one overrides __setattr__).


                          Michele




More information about the Python-list mailing list