Accessing public attributes of Python class in Java with Jython -
to access python objects in java using jython, it's necessary create java interface , use coersion (pyobject.__java__()) assign object java reference. (http://www.jython.org/faq2.html)
the problem python library i'm trying use not have gets , sets, , don't want change library code if can.
is there way public variables without having implement python classes subclass , expose attributes through methods?
thanks.
you can access attributes pyobject directly using __getattr__(pystring) , __setattr__(pystring, pyobject) methods.
you can attribute with:
pyobject pyobject = ...; // attribute: value = getattr(obj, name) // or: value = obj.__getattr__(name) pystring attrname = py.newstring("some_attribute"); pyobject attrvalue = pyobject.__getattr__(attrname); - warning: make sure use
__getattr__(pystring)because__getattr__(string)works interned strings.
you can set attribute with:
pyobject pyobject = ...; // set attribute: setattr(obj, name, value) // or: obj.__setattr__(name, value) pystring attrname = py.newstring("some_attribute"); pyobject attrvalue = (pyobject)py.newstring("a string new value."); pyobject.__setattr__(attrname, attrvalue); note: value not have
pystring. haspyobject.warning: make sure use
__setattr__(pystring, pyobject)because__setattr__(string, pyobject)works interned strings.
also, can call python method using __call__(pyobject[] args, string[] keywords):
pyobject pyobject = ...; // method: method = getattr(obj, name) // or: method = obj.__getattr__(name) pystring methodname = py.newstring("some_method"); pyobject pymethod = pyobject.__getattr__(methodname); // prepare arguments. // note: args contains positional arguments followed keyword argument values. pyobject[] args = new pyobject[] {arg1, arg2, ..., kwarg1, kwarg2, ...}; string[] keywords = new string[] {kwname1, kwname2, ...}; // call method: result = method(arg1, arg2, ..., kwname1=kwarg1, kwname2=kwarg2, ...) pyobject pyresult = pymethod.__call__(args, keywords); - note: cannot explain why keyword names
stringhere when getting attribute name requirespystring.
Comments
Post a Comment