From: Oti <oh...@ya...> - 2002-07-04 06:56:40
|
Hello developers, Motivation: ----------- if a java class X implements methods __add__() __sub__(), ... these methods are invoked if i use x = X() x + 10 x - 10 in the interpreter. Similarly, if X implements methods __eq__(), __lt__(), ... these methods are invoked if i use x = X() x == 10 x < 10 in the interpreter. This is cool, pretty cool i'd say ! In both cases it is the java class' responsibility to do and/or return something useful. Idea / Question: ---------------- Now it would be even cooler if methods __getattr__() __setattr__() would be invoked if i use x = X() x.undefinedAttribute x.undefinedAttribute = 10 x.undefinedMethod() Again it would be the java class' responsibility to do and/or return something useful. What do you think of this idea ? It can be done: --------------- The following two little changes (against the 2.1 codebase) enable the above. I am using this extensively for much closer Jython/Java integration. Is it worth opening a patch ? 1) File /core/PyJavaInstance.java: Old method: protected void noField(String name, PyObject value) { throw Py.TypeError("can't set arbitrary attribute in java instance: "+ name); } replaced with: protected void noField(String name, PyObject value) { PyObject method = __class__.lookup("__setattr__", false); if ( method == null ) { throw Py.TypeError("can't set arbitrary attribute in java instance: " + name); } else { method.__call__(this, new PyString(name), value); } } 2) File /core/PyInstance.java: Old method: protected PyObject ifindfunction(String name) { PyObject getter = __class__.__getattr__; if (getter == null) return null; try { return getter.__call__(this, new PyString(name)); } catch (PyException exc) { if (Py.matchException(exc, Py.AttributeError)) return null; throw exc; } } replaced with: protected PyObject ifindfunction(String name) { PyObject getter = __class__.__getattr__; if ( getter == null && __class__.getProxyClass() != null ) { getter = __class__.lookup("__getattr__", false); } if ( getter == null ) { return null; } try { return getter.__call__(this, new PyString(name)); } catch (PyException exc) { if (Py.matchException(exc, Py.AttributeError)) return null; throw exc; } } Many thanks for your feedback. Always-trying-to-make-jython-even-more-useful-ly yours Oti. __________________________________________________ Do You Yahoo!? Sign up for SBC Yahoo! Dial - First Month Free http://sbc.yahoo.com |