Type emulation issues with new style classes

Greg Chapman glc at well.com
Sat Feb 28 14:27:28 EST 2004


On Sat, 28 Feb 2004 11:33:54 GMT, "Chris" <feb04.20.netman at spamgourmet.com>
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

The following allows your test case to work, but it may have various subtle
problems.  AddDynOper emulates __getattr__ semantics: the descriptor is not
installed if the type already has an attribute of the given name:

class DynOperDescr(object):
    def __init__(self, name):
        self.name = name
    def __get__(self, instance, typ):
        if instance is None:
            return self
        return instance.__getattr__(self.name)

def AddDynOper(declcls, name):
    if not hasattr(declcls, name):
        setattr(declcls, name, DynOperDescr(name))

class Z(object):
    value = 42
    def __getattr__(self, name):
        if name == "__int__":
            return lambda : self.value
        raise AttributeError(name)
AddDynOper(Z, "__int__")

---
Greg Chapman




More information about the Python-list mailing list