【问题标题】:Convert from Java to Python从 Java 转换为 Python
【发布时间】:2019-08-28 16:26:36
【问题描述】:

我是 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; 的等价物是什么?如何调用另一个类?

这会是上述p​​ython中的某种等价物吗?我将如何在 python 中将这两个类链接在一起?

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:感谢到目前为止回答的所有人。如果我在课堂上有类似的东西,只是为了澄清一件事示例:

void exampleSomething(Example exampleb, String a){
        somethings.add(new Something(a, another));
    }

在 python 中是这样的:

def exampleSomething(another, a):
    self.somethings.append(a, another)

再次感谢

【问题讨论】:

  • 您的问题只是“在 Python 中什么相当于 Java ArrayList
  • Python中没有ArrayLists,默认只有List结构
  • 不同的问题,我的问题主要是那段代码的实现是否正确,如何在python中调用类内的类

标签: java python arrays list class


【解决方案1】:
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();
    }
}

【讨论】:

    【解决方案2】:

    让我们看看:

    class Example():
        def __init__(self):
            self.test= False
            self.somethings= []
    
    .
    .
    .
    
    class Something:
        def __init__(self, another, whatever):
            self.another = another 
            self.whatever = whatever 
    .
    .
    .
    

    应该没问题。但是你所有的班级成员都是公开的。让我们将它们设为私有:

    class Example():
        def __init__(self):
            self._test= False
            self._somethings= []
    
    .
    .
    .
    
    class Something:
        def __init__(self, another, whatever):
            self._another = another 
            self._whatever = whatever 
    .
    .
    .
    

    要添加 getter 和 setter,请查看 @property 装饰器:https://www.programiz.com/python-programming/methods/built-in/property

    现在,你想要类型吗?在 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 
    .
    .
    .
    

    ArrayList 就变成了list() - 一种随处可用的内置类型。

    【讨论】:

    • 更新后,我将如何添加类似于我上次编辑的内容,即 EDIT 2?
    • self.somethings.append(Someting(a, another)) 使用类名后跟() 来调用构造函数。
    【解决方案3】:

    一些关键区别

    • list 是内置在 python 中的。就做x = [1, 2, 3]
    • 没有私人。按照惯例,您可以在“私有”变量名称前加上 _,但没有什么可以阻止其他人访问它们。
    • 在课堂内,您必须在任何地方使用thisthis在python中通常称为self
    • 在类主体(外部方法)内声明变量会使它们成为类变量,而不是实例变量(类似于 java 中的 static

    对象的调用就像在 java 中一样。当你在另一个类中有对obj的引用时,只需调用obj.f(x)

    【讨论】:

    • 更新后,我将如何添加类似于我上次编辑的内容,即 EDIT 2?
    【解决方案4】:

    要在Python 中导入一个类,如果该类要放在单独的文件中,只需使用:

    import fileName
    

    在第二个文件的开头

    在你的情况下,你会:

    import example
    

    【讨论】:

    • 非常感谢!以及如何调用类实例?
    • 你只需要像 Java 那样做x = Example()
    • 更新后,我将如何添加类似于我上次编辑的内容,即 EDIT 2?
    • 是的,看起来不错
    猜你喜欢
    • 2022-01-12
    • 2021-08-28
    • 2014-05-14
    • 2018-06-11
    • 2021-11-01
    • 1970-01-01
    • 2016-12-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多