类的定义
- class classname[(父类名)]:
– 成员函数及成员变量 - _ init _ 构造函数:初始化对象
- _ del_ 析构函数:销毁对象
- 定义类的成员函数时,必须默认一个变量代表类定义的对象本身,这个变量的名称可自行定义,下面的程序使用self变量表示类对象的变量
Python-class简单操作
为了学习python中class,我们编写一个简单的程序。我们的任务是找到stduents.txt文件中,GPA最高的那名同学,并打印出他的信息
其中students.txt文件中的内容如下:
zhangsan 127 228
lisi 100 400
wangwu 18 41.5
maliu 48.5 155
sunqi 37 125.33
# 找到GPA最高的学生
class Student:def __init__(self, name, hours, qpoints):self.name = nameself.hours = float(hours)self.qpoints = float(qpoints)def getName(self):return self.namedef getHours(self):return self.hoursdef getQPoint(self):return self.qpointsdef gpa(self):return self.qpoints/self.hoursdef makeStudent(infoStr):infoStr = infoStr.strip("\n")name, hours, qpoints = infoStr.split(" ")return Student(name, hours, qpoints)def main():filename = "students.txt"infile = open(filename, "r")best = makeStudent(infile.readline())for line in infile:s = makeStudent(line)if s.gpa() > best.gpa():best = sinfile.close()print("The best student is:", best.getName())print("hours:", best.getHours())print("GPA:", best.gpa())if __name__ == "__main__":main()
输出结果如下
D:\Python36\python.exe E:/Code/python/class/student1.py
The best student is: lisi
hours: 100.0
GPA: 4.0