Jython 2.1 __getattr__
我正在尝试在 jython v2.1 中为 java 对象(baseClient)实现包装器/代理类。一切似乎都工作正常,除非遇到以下语句:
if __client != None # __client is an instance of the ClientProxy class
在 __getattr__()
中调用 raise AttributeError(attr)
,因为 self.__baseClient
> 没有 __ne__
属性。 值得一提的是,我无法升级,因为 jython 是系统的一部分。有办法解决这个问题吗?
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
多谢!
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 statement 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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
为了针对特定实例(例如 None)进行测试,通常使用恒等运算符:
这将避免调用比较器的问题。
然而,事实上
__getattr__
引发AttributeError
应该不是问题。比较器应该推测性地调用getattr
来获取__cmp__
(在较新的 Python 上首先调用__ne__
),并且如果它得到一个AttributeError
它应该默默地吞掉它,然后退回到身份比较。为什么AttributeError
在您的案例中会导致问题?For testing against specific instances such as None, it's idiomatic to use the identity operator:
This will avoid the problem of calling comparators.
However, the fact that
__getattr__
raisesAttributeError
should not be a problem. The comparator should callgetattr
speculatively for__cmp__
(__ne__
first on newer Pythons), and if it gets anAttributeError
it is supposed to silently swallow it and fall back to identity comparison instead. Why does theAttributeError
cause a problem in your case?