[英]Convert from Java to Python
I am new to python and I'm wondering how one would go around to convert a piece of code in this case Java to python.我是 python 的新手,我想知道在这种情况下如何将一段代码转换为 python。 For instance if a public class Example
is a class which consists of multiple functions for instance:例如,如果一个公共类Example
是一个由多个函数组成的类,例如:
File 1:文件 1:
public class Example{
private ArrayList<Something> somethings;
private boolean test;
foo(){
test= false;
somethings = new ArrayList<>();
}
.
.
.
File 2:文件2:
class Something{
private Example another;
private String whatever;
Something(String a, Node another){
this.another = another ;
this.whatever = whatever;
}
.
.
.
In python what is the equivalent of import java.util.ArrayList;
在 python 中什么相当于import java.util.ArrayList;
and how would one go about it to call another class?以及如何调用另一个类?
Will this be some sort of the above's equivalent in python?这会是python中的某种上述等价物吗? How would I go about linking the 2 classes together in 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
.
.
.
Thanks in advance提前致谢
EDIT 1: My questions mainly are If the implementation of that piece of code are correct and how to call a class within a class in python编辑 1:我的问题主要是那段代码的实现是否正确以及如何在 python 中的类中调用类
EDIT 2:Thanks for everyone who answered so far.编辑 2:感谢到目前为止所有回答的人。 Just to clarify with one more thing if I had something like which is in class Example:只是为了澄清一件事,如果我在课堂上有类似的东西示例:
void exampleSomething(Example exampleb, String a){
somethings.add(new Something(a, another));
}
in python would this be the following:在python中,这将是以下内容:
def exampleSomething(another, a):
self.somethings.append(a, another)
Thanks once again再次感谢
Some key differences一些关键差异
list
is built-in in python. list
是python内置的。 Just do x = [1, 2, 3]
只做x = [1, 2, 3]
_
, but nothing can stop others from accessing them.按照惯例,您在“私有”变量名前加上_
,但没有什么可以阻止其他人访问它们。this
everywhere.在课堂上,你必须在任何地方使用this
。 this
is commonly called self
in python this
在python中通常称为self
static
in java)在类体内(外部方法)声明变量使它们成为类变量,而不是实例变量(类似于 java 中的static
变量) Objects are called just like in java.对象的调用就像在 java 中一样。 When you have a reference to obj
in another class, just call obj.f(x)
当您在另一个类中引用obj
时,只需调用obj.f(x)
import java.util.Random;
/**
*
* @author Vijini
*/
//Main class
public class SimpleDemoGA {
Population population = new Population();
Individual fittest;
Individual secondFittest;
int generationCount = 0;
public static void main(String[] args) {
Random rn = new Random();
SimpleDemoGA demo = new SimpleDemoGA();
//Initialize population
demo.population.initializePopulation(10);
//Calculate fitness of each individual
demo.population.calculateFitness();
System.out.println("Generation: " + demo.generationCount + " Fittest: " + demo.population.fittest);
//While population gets an individual with maximum fitness
while (demo.population.fittest < 5) {
++demo.generationCount;
//Do selection
demo.selection();
//Do crossover
demo.crossover();
//Do mutation under a random probability
if (rn.nextInt()%7 < 5) {
demo.mutation();
}
//Add fittest offspring to population
demo.addFittestOffspring();
//Calculate new fitness value
demo.population.calculateFitness();
System.out.println("Generation: " + demo.generationCount + " Fittest: " + demo.population.fittest);
}
System.out.println("\nSolution found in generation " + demo.generationCount);
System.out.println("Fitness: "+demo.population.getFittest().fitness);
System.out.print("Genes: ");
for (int i = 0; i < 5; i++) {
System.out.print(demo.population.getFittest().genes[i]);
}
System.out.println("");
}
//Selection
void selection() {
//Select the most fittest individual
fittest = population.getFittest();
//Select the second most fittest individual
secondFittest = population.getSecondFittest();
}
//Crossover
void crossover() {
Random rn = new Random();
//Select a random crossover point
int crossOverPoint = rn.nextInt(population.individuals[0].geneLength);
//Swap values among parents
for (int i = 0; i < crossOverPoint; i++) {
int temp = fittest.genes[i];
fittest.genes[i] = secondFittest.genes[i];
secondFittest.genes[i] = temp;
}
}
//Mutation
void mutation() {
Random rn = new Random();
//Select a random mutation point
int mutationPoint = rn.nextInt(population.individuals[0].geneLength);
//Flip values at the mutation point
if (fittest.genes[mutationPoint] == 0) {
fittest.genes[mutationPoint] = 1;
} else {
fittest.genes[mutationPoint] = 0;
}
mutationPoint = rn.nextInt(population.individuals[0].geneLength);
if (secondFittest.genes[mutationPoint] == 0) {
secondFittest.genes[mutationPoint] = 1;
} else {
secondFittest.genes[mutationPoint] = 0;
}
}
//Get fittest offspring
Individual getFittestOffspring() {
if (fittest.fitness > secondFittest.fitness) {
return fittest;
}
return secondFittest;
}
//Replace least fittest individual from most fittest offspring
void addFittestOffspring() {
//Update fitness values of offspring
fittest.calcFitness();
secondFittest.calcFitness();
//Get index of least fit individual
int leastFittestIndex = population.getLeastFittestIndex();
//Replace least fittest individual from most fittest offspring
population.individuals[leastFittestIndex] = getFittestOffspring();
}
}
//Individual class
class Individual {
int fitness = 0;
int[] genes = new int[5];
int geneLength = 5;
public Individual() {
Random rn = new Random();
//Set genes randomly for each individual
for (int i = 0; i < genes.length; i++) {
genes[i] = Math.abs(rn.nextInt() % 2);
}
fitness = 0;
}
//Calculate fitness
public void calcFitness() {
fitness = 0;
for (int i = 0; i < 5; i++) {
if (genes[i] == 1) {
++fitness;
}
}
}
}
//Population class
class Population {
int popSize = 10;
Individual[] individuals = new Individual[10];
int fittest = 0;
//Initialize population
public void initializePopulation(int size) {
for (int i = 0; i < individuals.length; i++) {
individuals[i] = new Individual();
}
}
//Get the fittest individual
public Individual getFittest() {
int maxFit = Integer.MIN_VALUE;
int maxFitIndex = 0;
for (int i = 0; i < individuals.length; i++) {
if (maxFit <= individuals[i].fitness) {
maxFit = individuals[i].fitness;
maxFitIndex = i;
}
}
fittest = individuals[maxFitIndex].fitness;
return individuals[maxFitIndex];
}
//Get the second most fittest individual
public Individual getSecondFittest() {
int maxFit1 = 0;
int maxFit2 = 0;
for (int i = 0; i < individuals.length; i++) {
if (individuals[i].fitness > individuals[maxFit1].fitness) {
maxFit2 = maxFit1;
maxFit1 = i;
} else if (individuals[i].fitness > individuals[maxFit2].fitness) {
maxFit2 = i;
}
}
return individuals[maxFit2];
}
//Get index of least fittest individual
public int getLeastFittestIndex() {
int minFitVal = Integer.MAX_VALUE;
int minFitIndex = 0;
for (int i = 0; i < individuals.length; i++) {
if (minFitVal >= individuals[i].fitness) {
minFitVal = individuals[i].fitness;
minFitIndex = i;
}
}
return minFitIndex;
}
//Calculate fitness of each individual
public void calculateFitness() {
for (int i = 0; i < individuals.length; i++) {
individuals[i].calcFitness();
}
getFittest();
}
}
To import a class in Python
, if the class is to be in a separate file, just use :要在Python
导入类,如果类要在单独的文件中,只需使用:
import fileName
at the beginning of you second file在你第二个文件的开头
In your case, you would :在你的情况下,你会:
import example
Let's see:让我们来看看:
class Example():
def __init__(self):
self.test= False
self.somethings= []
.
.
.
class Something:
def __init__(self, another, whatever):
self.another = another
self.whatever = whatever
.
.
.
Should be fine.应该没事。 But all your class members are public.但是你所有的班级成员都是公开的。 Let's make them private:让我们将它们设为私有:
class Example():
def __init__(self):
self._test= False
self._somethings= []
.
.
.
class Something:
def __init__(self, another, whatever):
self._another = another
self._whatever = whatever
.
.
.
To add getters and setters checkout the @property
decorator: https://www.programiz.com/python-programming/methods/built-in/property要添加 getter 和 setter, @property
查看@property
装饰器: https : //www.programiz.com/python-programming/methods/built-in/property
Now, do you want types?现在,你想要类型吗? In python 3+ you can have types: https://docs.python.org/3/library/typing.html在 python 3+ 中你可以有类型: https : //docs.python.org/3/library/typing.html
class Example():
def __init__(self):
self._test= False
self._somethings= []
.
.
.
class Something:
def __init__(self, another -> str, whatever -> Node):
self._another = another
self._whatever = whatever
.
.
.
And ArrayList
becomes just list()
- a builtin type that's available everywhere. ArrayList
变成了list()
—— 一种随处可用的内置类型。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.