|
From: Jim A. <ji...@tr...> - 2001-03-29 00:24:18
|
Finn Bock wrote:
>
> This is a correct way to set/get attributes:
>
> classInstance.__setattr__( key1.intern(),
> new PyString("In my code this is actually a PyList object..." ));
> ...
I had missed the requirement to 'intern' Strings in the docs: yes this
works with 'identityHashCode()'.
Of course this makes my other changes from '==' -> '.equals' unnecessary
also.
Besides the API docs, there is not much info on the jython site about
this kind of use of Jython.
Would it be useful if I could try to put something together? Maybe a new
item in 'Working with Java' section ?
For example, I have some test code that compares this:
String s = "class Charge: pass \n" +
"c1 = Charge() \n" +
"c1.Code = 'AF' \n" +
"c1.Description = 'Appraisal Fee' \n" +
"c1.Amount = '100' \n" +
"c1.PaidTo = 'L' \n" +
"c3 = Charge() \n" +
"c3.Code = 'MSC' \n" +
"c3.Description = 'Misc Fee 1' \n" +
"c3.Amount = '200' \n" +
"c3.PaidTo = 'L' \n" +
"c4 = Charge() \n" +
"c4.Code = 'MSC' \n" +
"c4.Description = 'Misc Fee 2' \n" +
"c4.Amount = '300' \n" +
"c4.PaidTo = 'L' \n" +
...
"ChargeList = [c1, c2, c3, c4] \n" +
With this:
pi.exec( "class Charge: pass" );
PyClass Charge = (PyClass)pi.get("Charge"); // Get the Class itself
!
PyInstance c1 = new PyInstance( Charge ); // Build a new instance
of the class
c1.__setattr__( "Code".intern(), new PyString("AF") );
c1.__setattr__( "Description".intern(), new PyString("Appraisal
Fee") );
c1.__setattr__( "Amount".intern(), new PyInteger(
Integer.parseInt("100") ) );
PyInstance c2 = new PyInstance( Charge); // Another instance of
the class
c2.__setattr__( "Code".intern(), new PyString("MSC") );
c2.__setattr__( "Description".intern(), new PyString("Misc Fee 1")
);
c2.__setattr__( "Amount".intern(), new PyInteger(
Integer.parseInt("200") ) );
...
PyList ChargeList = new PyList();
ChargeList.append(c1);
ChargeList.append(c2);
ChargeList.append(c3);
pi.set("ChargeList", ChargeList );
Both allow Jython code such as this to execute:
Total = 0
for C in ChargeList:
print C.Code,C.Amount
Total += C.Amount
The advantage to the second (Java) approach is that it is easier to make
everything dynamic (for example based on XML or Database definitions).
In effect the 'words' in your database definitions because 'part of' the
scripting language from a 'non-programming user' perspective.
Let me know if you think this kind of approach is general enough to be
worth documenting on the site, and I can put something more detailed
together based on my current project.
--
__o
Jim Adrig _ \<,_
ji...@tr... ' `/ ' `
___________ `-' `-'
|