1. 为什么要有类和对象
我们如何把多个数据当成一个变量来使用呢,在C语言中我们用struct来表示
struct Student {
string name;
int age;
double score;
}
我们可以这么来使用他
#include<stdio.h>
int main() {
Student s;
s.name = "liyunyang";
s.age = 18;
s.score = 98.5;
}
这样我们就可以把多个属性聚集到一起,方便访问。
我们换做Java来写是这样
class Student {
String name;
int age;
double score;
}
public class Hello {
public static void main(String[] args) {
Student s = new Student();
s.name = "李云阳";
s.age = 18;
s.score = 98.5;
}
}
换做Python我们这么写
class Student:
name = ""
age = 0
score = 0.0
s = Student()
s.name = "liyunyang"
s.age = 18
s.score = 98.5
2. 类和对象的关系和封装思想
类就是模板,对象就是具体的数。举个例子类就是int这个类型,而对象就是具体的数比如12
类还可以设置隐私关系,在Java中我们这么写
class Student {
public String name;
public int age;
private double score;
}
python我们这么写
class Student:
name = ""
age = 0
__score = 0.0
3. 类的继承关系
class Student {
public String name;
public int age;
private double score;
}
class HighSchoolStudent extends Student {
private String school;
}
public class Hello {
public static void main(String[] args) {
HighSchoolStudent s = new HighSchoolStudent();
s.name = "liyuyang";
s.age = 18;
}
}
class Student:
name = ""
age = 0
__score = 0.0
class HighSchoolStudent(Student):
__school = ""
4. 类的方法
C语言中student只能定义属性,C++,Java,Python都可以定义方法
Java中
class Student {
public String name;
public int age;
private double score;
String sayName() {
return name;
}
}
class HighSchoolStudent extends Student {
private String school;
}
public class Hello {
public static void main(String[] args) {
HighSchoolStudent s = new HighSchoolStudent();
s.name = "liyuyang";
s.age = 18;
String str = s.sayName();
}
}
python中
class Student:
name = ""
age = 0
__score = 0.0
def sayName(self):
return "我的名字是:" + self.name
class HighSchoolStudent(Student):
__school = ""
s = Student()
s.name = "lyy"
print(s.sayName())
1. 如何获取私有属性和设置私有属性
class Student {
public String name;
public int age;
private double score;
public double getScore() {
return score;
}
public void setScore(double score) {
this.score = score
}
}
class HighSchoolStudent extends Student {
private String school;
}
public class Hello {
public static void main(String[] args) {
HighSchoolStudent s = new HighSchoolStudent();
s.name = "liyuyang";
s.age = 18;
s.setScore(98.5);
}
}
python中
class Student:
name = ""
age = 0
__score = 0.0
def getScore(self):
return self.__score
def setScore(self, score):
self.__score = score
class HighSchoolStudent(Student):
__school = ""
s = Student()
s.name = "lyy"
s.setScore(98.5)
print(s.getScore())
5. Object是什么东西
我们都知道,类是有继承关系的,那么所有的类,都默认继承自Object
Java中下面写法是一样的
class Student {}
class Student extends Object {}
Python中是这样
class Student:
class Student(Object):