Java类是在与类同名的文件中定义的。因此,必须将该类保存在一个名为Car.java的文件中。每个文件中只能定义一个类。
public class Car { private String color; private String model; private int year; public Car(String color, String model, int year) { this.color = color; this.model = model; this.year = year; } public String getColor() { return color; } public String getModel() { return model; } public int getYear() { return year; } }在Python中,可以随时在任何文件中声明任何类。 将此类保存在car.py文件中。
class Car: def __init__(self, color, model, year): self.color = color self.model = model self.year = year在Java中,可以在类体中声明具有明确类型的任何方法之外的属性。 必须在使用之前定义类属性:
public class Car { private String color; private String model; private int year;在Python中,在类__init __()中声明和定义属性,这相当于Java的构造函数
def __init__(self, color, model, year): self.color = color self.model = model self.year = year也可以在.__ init __()之外创建实例变量,但是不推荐。
摘选原文:https://realpython.com/oop-in-python-vs-java/
转载于:https://www.cnblogs.com/c-x-a/p/10977996.html