Python面向对象——创建类:学生成绩等级

题目:

不同分数对应等级,score >= 90分为“优秀”,80 <= score < 90为“良好”,70 <= score < 80为“中等”,60 <= score < 70为“及格”,score < 60为“不及格”。

1 学习创建类

采用class

class Person:#创建类
    country = "Chinese" #类属性,可以通过类名来访问
    def __init__(self,name,age):  #构造函数_init_,构造函数中定义的参数是实例属性,self表示当前对象
        self.name = name
        self.age = age
        
    def detail(self):
        print(self.name)
        print(self.age)
        print(self.country)
    def f(self):#类中函数的第一个参数,表示当前对象
        print("这个是Person类的一个普通函数")

创建对象并调用类中构造函数:

zs = Person("js",22)   #创建对象zs
zs.detail()   #调用Person类下的构造函数detail(self)

输出:

js
22
Chinese

调用zs的某一属性:

zs.country

输出:

'Chinese'

 

2 题目答案

代码实现:

class Student:
    def __init__(self,name,score):  #构造方法self表示当前对象,name和score是实例属性
        self.name = name
        self.score = score
    def get_grade(self):
        if self.score >= 90:
            s = "优秀"
        elif self.score >= 80:
            s = "良好"
        elif self.score >= 70:
            s = "中等"
        elif self.score >= 60:
            s = "及格"
        else:
            s = "不及格"
        print(s)
        return s
    def show(self):
        print("姓名:{},分数:{},等级:{}".format(self.name,self.score,self.get_grade()))

创建对象并调用类中方法:

lucy = Student("Lucy",95)
lucy.show()

输出:

优秀
姓名:Lucy,分数:95,等级:优秀  #又调用了一下show方法

 

总结:主要学习了类的定义及类方法的编写及调用。

posted @ 2024-05-27 16:35  颍2333  阅读(40)  评论(0编辑  收藏  举报