Type emulation issues with new style classes

Chris feb04.20.netman at spamgourmet.com
Sat Feb 28 14:45:14 EST 2004


I'm looking for a way to do this without explicity definining every
emulation method, i.e. (__str__, __lt__, __le__, __eq__, __ne__, __gt__,
__ge__, __len__, __getitem__, __add__, __sub__, __mul__, __floordiv__,
__mod__, __divmod__, __pow__, __lshift__, ... ad nausuem).  Plus, there's a
few this isn't going to work for several of the the arithmetic operators,
such as when I want to have __add__ undefined so Python will attpemt
__radd__.  For example:

class Y:
    value = 42
    def __getattr__(self, name):
        if name == '__coerce__':
            raise AttributeError
        if name == '__add__':
            raise AttributeError
        if name == '__radd__':
            return lambda other: self.value + other.value

>>> y1, y2 = Y(), Y()
>>> print int(y1)       #This works
42
>>> print y1 + y2       #This works too
84

class Z(object):
    value = 42
    def __getattr__(self, name):
        if name == '__add__':
            raise AttributeError
        if name == '__radd__':
            return lambda other: Z.value + Z.value
        if name == '__int__':
            return lambda: self.value
    def __int__(self):
        return self.__getattr__('__int__')()
    def __add__(self, other):
        return self.__getattr__('__add__')()
    def __radd__(self, other):
        return self.__getattr__('__radd__')()


>>> z1, z2 = Z(), Z()
>>> # This following will work now, after explicitly
>>> # adding __int__ to the namespace of Z, which I'm
>>> # trying to avoid.
>>> print int(z1)
42
>>> print y1 + y2  # This bombs
TypeError: 'NoneType' object is not callable

"Rainer Deyke" wrote:
> Chris wrote:
> > class Z(object):
> >     value = 42
> >     def __hasattr__(self, name):
> >         if name == '__int__':
> >             return True
> >     def __getattr__(self, name):
> >         if name == '__int__':
> >             return lambda: self.value
>       def __int__(self):
>         return self.__getattr__('__int__')()
>
>
> -- 
> Rainer Deyke - rainerd at eldwood.com - http://eldwood.com
>
>





More information about the Python-list mailing list