New PEP: Attribute Access Handlers

Gordon McMillan gmcm at hypernet.com
Sat Jul 22 16:33:13 EDT 2000


Paul Prescod wrote:

>Consider this module and tell me what it would output (in your opinion):
>
>class A:
>    def __set_x__( self, val ):
>        print val
>a=A()
>a.x=5
5
>print a.x
AttributeError
>del a.x
AttributeError

So far, it's unambiguous.

>
>class B(A):
>    def __get_x__( self, val ):
>       return "funny walk"
>
>b=B()
>b.x=5
5
>print b.x
funny walk
>del b.x
AttributeError

>Now, how would you implement it?

class proxy:
    def __init__(self, obj):
        self.__dict__['_obj'] = obj
    def __getattr__(self, nm):
        mnm = '__get_%s__' % nm
        mthd = getattr(self._obj, mnm, None)
        if mthd:
            return mthd()
        return getattr(self._obj, nm)
    def __setattr__(self, nm, val):
        mnm = '__set_%s__' % nm
        mthd = getattr(self._obj, mnm, None)
        if mthd:
            return mthd(val)
        setattr(self._obj, nm, val)
    def __delattr__(self, nm):
        mnm = '__del_%s__' % nm
        mthd = getattr(self._obj, mnm, None)
        if mthd:
            mthd()
        delattr(self._obj, nm)

class _A:
    def __set_x__(self, val):
        print val
class _B(_A):
    def __get_x__(self):
        return "funny walk"

def A():
    return proxy(_A())

def B():
    return proxy(_B())


-Gordon



More information about the Python-list mailing list