Jython中导入的类中缺少属性

时间:2013-05-23 10:47:26

标签: java python jython

我宣布了一个Java类 -

class Beach {
    private String name, city;

    public Beach(String name, String city) {
        this.name = name;
        this.city = city;
    }
}

我将它导入jython并尝试创建一个对象 -

import Beach
b = Beach("candolim", "goa")


Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: java.lang.Object(): expected 0 args; got 2

我的两个参数构造函数在哪里?

修改

我遵循这些确切的步骤 -

// Comment - Remove all files from directory to not create any confusion.
$ rm -rf *

$ vi Beach.java

class Beach {
private String name, city;

public Beach(String name, String city) {
  this.name = name;
  this.city = city;
 }
}

$ javac *.java
$ javap Beach

Compiled from "Beach.java"
class Beach {
  public Beach(java.lang.String, java.lang.String);
}


$ jython
>>> import Beach
>>> b = Beach()
>>> dir(b)

['__class__', '__copy__', '__deepcopy__', '__delattr__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', '__subclasshook__', '__unicode__', 'class', 'equals', 'getClass', 'hashCode', 'notify', 'notifyAll', 'toString', 'wait']

1 个答案:

答案 0 :(得分:2)

看起来您没有使用问题中显示的Java类。我可以重现错误。

beach.py​​:

import Beach

b = Beach("candolim", "goa")
print b.__class__

Beach.java alt。 1(零构造函数参数):

public class Beach {
  private String name, city;

  public Beach() {
  }
}

使用Beach.java alt时的输出。 1:

$ jython beach.py
Traceback (most recent call last):
  File "beach.py", line 3, in <module>
    b = Beach("candolim", "goa")
TypeError: Beach(): expected 0 args; got 2

Beach.java alt。 2(问题中的类;两个参数):

public class Beach {
private String name, city;

public Beach(String name, String city) {
  this.name = name;
  this.city = city;
 }
}

使用Beach.java alt时的输出。 2:

$ jython beach.py
<type 'Beach'>

编辑:似乎有些奇怪的事情发生了。当我尝试按照编辑过的问题中的步骤时会发生以下情况:

$ rm *.class
$ cat Beach.java
public class Beach {
    private String name, city;

    public Beach(String name, String city) {
        this.name = name;
        this.city = city;
    }
}
$ javac Beach.java
$ javap Beach
Compiled from "Beach.java"
public class Beach {
  public Beach(java.lang.String, java.lang.String);
}
$ jython
Jython 2.7b1 (default:ac42d59644e9, Feb 9 2013, 15:24:52)
[Java HotSpot(TM) 64-Bit Server VM (Oracle Corporation)] on java1.7.0_15
Type "help", "copyright", "credits" or "license" for more information.
>>> import Beach
>>> b = Beach()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Beach(): expected 2 args; got 0
>>>

请注意javap输出不同。这里写着public class Beach。问题只是class Beach