Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jython AttributeError: read-only attr

I am trying to write a program about a .py extend a java interface, just like an example on IBM developerworks.

But I got a problem like:

AttributeError: read-only attr: cardID

But the strange thing is if I rename the cardID to cardNum,it works. Here my code:

CardInfo.py

from com.jyt import CardInfo
class CardInfo(CardInfo):
    def __init__(self):
        self.cardName = "Dark Magician"
        self.cardID = "888"

    def getName(self):
        return self.cardName

    def getCardID(self):
        return self.cardID

    def setID(self,newID):
        self.cardID = newID  

and the java interface:

public interface CardInfo {
    public String getCardID();
    public String getName();
    public void setID();
}

and the java file

        Object javaObject;
        PythonInterpreter interpreter = new PythonInterpreter();
//      PySystemState sys = Py.getSystemState();
        interpreter.execfile("./res/CardInfo.py");
        interpreter.exec("cardInfo=CardInfo()");
        PyObject pyObject = interpreter.get("cardInfo");
        pyObject.invoke("setID",new PyString("12345"));
        try{
            javaObject = pyObject.__tojava__(CardInfo.class);
            CardInfo cardInfo = (CardInfo)javaObject;
            System.out.println(cardInfo.getCardID());
            System.out.println(cardInfo.getName());
        }catch(Exception e){
            e.printStackTrace();
        }

anyone knows how to solve this?

like image 729
user1746290 Avatar asked Oct 07 '22 08:10

user1746290


1 Answers

This is just a guess (can't test it right now because I'm not on my own pc), but your problem is probably related to the (somewhat underdocumented) fact that jython generates property accessors for javas getter/setter methods, which clash with your attribute names and thus shadow your actual attribute.

If my hypothesis is correct, the problem in this case is that you have a getter method which has the same name (minus the get part) as the attribute. Jython sees the method and generates a property for it, which is read-only because there is no matching setter method.

It may be that you could fix this by just renaming your setID method to setCardID so jython correctly interprets the attribute as writable. If this doesn't work for some reason, one of the following should definitely work:

  • rename the attribute to something else, like self.myCardID
  • alternatively, rename the method to something else, like getID

Both of these solutions should cause the attribute to no longer be shadowed by the property accessor.

like image 149
l4mpi Avatar answered Oct 10 '22 02:10

l4mpi