我是python的新手,我想知道如何在这种情况下将Java转换为python的一段代码。例如,如果公共类Example
是包含多个功能的类,例如:
文件1:
public class Example{
private ArrayList<Something> somethings;
private boolean test;
foo(){
test= false;
somethings = new ArrayList<>();
}
.
.
.
档案2:
class Something{
private Example another;
private String whatever;
Something(String a, Node another){
this.another = another ;
this.whatever = whatever;
}
.
.
.
在python中,
import java.util.ArrayList;
的等效项是什么,如何调用它来调用另一个类?这会和上面的python等效吗?我将如何在python中将2个类链接在一起?
class Example():
def __init__(self):
self.test= False
self.somethings= []
.
.
.
class Something:
def __init__(self, another, whatever):
self.another = another
self.whatever = whatever
.
.
.
提前致谢
编辑1:我的问题主要是该代码的实现是否正确以及如何在python的类中调用类
编辑2:谢谢所有到目前为止回答的人。为了进一步说明一下,如果我在类Example中有类似的内容:
void exampleSomething(Example exampleb, String a){
somethings.add(new Something(a, another));
}
在python中将是以下内容:
def exampleSomething(another, a):
self.somethings.append(a, another)
再次感谢
最佳答案
一些关键差异list
是python内置的。只要做x = [1, 2, 3]
没有私人的。按照惯例,您可以在_
之前为“私有”变量名加上前缀,但是没有什么可以阻止其他人访问它们。
在类中,必须在任何地方使用this
。 this
在python中通常称为self
在类主体(外部方法)中声明变量会使它们成为类变量,而不是实例变量(类似于Java中的static
)
对象的调用就像在Java中一样。当您在另一个类中引用obj
时,只需调用obj.f(x)