开发者

Jython 2.1 __getattr__

开发者 https://www.devze.com 2022-12-11 12:39 出处:网络
I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following st开发者_开发知识库atement is encountered:

I am trying to implement a wrapper/proxy class for a java object (baseClient) in jython v2.1. Everything seems to be working ok except when the following st开发者_开发知识库atement is encountered:

if __client != None # __client is an instance of the ClientProxy class

raise AttributeError(attr) is called in __getattr__(), because self.__baseClient doesn't have __ne__ attribute. It's important to mention that I cannot upgrade because jython is a part of a system. Is there a way to get around this issue?

class ClientProxy:
    def __init__(self, baseClient):
        self.__baseClient = baseClient
        self.__initialised = 1

    def __getattr__(self, attr):
        if not self.__dict__.has_key('_ClientProxy__initialised'):
            raise AttributeError(attr)
        else:
            if hasattr(self.__baseClient, attr):
                return getattr(self.__baseClient, attr)
            else:
                raise AttributeError(attr)


    def __setattr__(self, attr, val):
        if not self.__dict__.has_key('_ClientProxy__initialised'):
            self.__dict__[attr] = val
            return

        if hasattr(self.__baseClient, attr):
            self.__baseClient.__setattr__(attr, val)
        else:
            self.__dict__[attr] = val

Thanks a lot!


if __client != None:

For testing against specific instances such as None, it's idiomatic to use the identity operator:

if __client is not None:

This will avoid the problem of calling comparators.

However, the fact that __getattr__ raises AttributeError should not be a problem. The comparator should call getattr speculatively for __cmp__ (__ne__ first on newer Pythons), and if it gets an AttributeError it is supposed to silently swallow it and fall back to identity comparison instead. Why does the AttributeError cause a problem in your case?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号