oop面向对象编程python

发布时间:2024年01月18日

1.定义一个圆类(Circle),求圆的面积和周长


import math


class Circle():
    def __init__(self, R ,name):
        self.radius = R
        self.name = name

    def girth(self):
        return 2 * self.radius * math.pi

    def area(self):
        return self.radius ** 2 * math.pi


c1= Circle(10,"c1")
c2= Circle(20,"c2")
c3= Circle(30,"c3")
print(f"{c1.name} girth is {c1.girth():.2f} and area is {c1.area():.2f}")
print(f"{c2.name} girth is {c2.girth():.2f} and area is {c2.area():.2f}")
print(f"{c3.name} girth is {c3.girth():.2f} and area is {c3.area():.2f}")

2.定义一个三角形类(Strange),属性是三边的长度,求三角形的面积和周长

# _*_ coding : utf-8 _*_
# @TIME : 2024/1/17 19:10
# @Author : gu
# @File : Triangle
# @Project : pytest
import math


class Triangle():
    def __init__(self,side1,side2,side3):
        lis=[side1,side2,side3]
        lis.sort()
        if lis[0]+lis[1]>=lis[2]:
            self.side1 = side1
            self.side2 = side2
            self.side3 = side3
        else:
            self.side1 = 0
            self.side2 = 0
            self.side3 = 0


    def girth(self):
        return self.side1 + self.side2 + self.side3

    def area(self):
        p=self.girth()/2
        area = math.pow((p*(p-self.side1)*(p-self.side2)*(p-self.side3)),0.5)
        return area

t2= Triangle(3,4,5)
t1= Triangle(1,3,5)
print(f"t1 girth is {t1.girth():.2f} and area is {t1.area():.2f}")
print(f"t2 girth is {t2.girth():.2f} and area is {t2.area():.2f}")

3.创建一个学员类,并设计三个字段用于表示学生的成绩(语文、数学、英语):然后定义一个列表表示一个班的学生(10人),依次输入每个学生的信息和成绩,输入的同时将学员的每科成绩划分等级(100-90:A ? ? 89-80:B ? ?79-70:C ? ?69-60:D 60以下:E)最后输出所有学员的信息

# _*_ coding : utf-8 _*_
# @TIME : 2024/1/17 19:30
# @Author : gu
# @File : Student
# @Project : pytest
class student():
    def __init__(self, name, math, eng, lan):
        self.name = name
        self.math = math
        self.eng = eng
        self.lan = lan

    @staticmethod
    def to_level(score):
        if score >= 90:
            return 'A'
        elif score >= 80:
            return 'B'
        elif score >= 70:
            return 'C'
        elif score >= 60:
            return 'D'
        elif score >= 0:
            return 'E'
        else:
            return '输入错误'

    def math_level(self):
        return self.to_level(self.math)

    def eng_level(self):
        return self.to_level(self.eng)

    def lan_level(self):
        return self.to_level(self.lan)

    def __str__(self):
        return f"姓名{self.name} 数学成绩{self.math} 语文成绩{self.lan} 英语成绩{self.eng}语文评级{self.lan_level()} 数学评级{self.math_level()} 英语评级{self.eng_level()} "



lis=['student1', 'student2', 'student3', 'student4', 'student5','student6', 'student7', 'student8', 'student9', 'student10']
s=['']*len(lis)
for i in range(0,len(lis)):
    scoree=input(f"输入{lis[i]}的成绩 分别是数学 英语 语文").split(',')
    score=list(map(int,scoree))
    s[i]=student(lis[i],score[0],score[1],score[2])
    print(f"{s[i].name} 的英语评级是{s[i].eng_level()} 语文评级{s[i].lan_level()} 数学评级{s[i].math_level()}")
for i in s:
    print(i)

4.编一个关于求某门功课总分和平均分的程序

- 每个学生的信息包括姓名和某门功课的成绩

- 假设5个学生

- 类和对象的处理要合理


class Student:
    def __init__(self, name, score):
        self.name = name
        self.score = score

    def get_total_score(self):
        return sum(self.score)

    def get_average_score(self):
        return sum(self.score) / len(self.score)


student1 = Student("张三", [90, 85, 80])
student2 = Student("李四", [95, 90, 75])
student3 = Student("王五", [80, 70, 60])
student4 = Student("赵六", [85, 75, 65])
student5 = Student("孙七", [70, 60, 50])

students = [student1, student2, student3, student4, student5]
def calculate_and_print(subject_index):
    total_score = 0 # 初始化总分为0
    for student in students: # 遍历所有的学生对象
        total_score += student.score[subject_index]
    average_score = total_score / len(students)
    print(f"该门功课的总分是{total_score},平均分是{average_score}")

calculate_and_print(0)
calculate_and_print(1)
calculate_and_print(2)

5.设计一个游戏角色类

字段:角色名、血量、魔法、状态

方法:释放技能 被伤害

要求:设计合理

# _*_ coding : utf-8 _*_
# @TIME : 2024/1/17 21:39
# @Author : gu
# @File : hero
# @Project : pytest

class Hero:
    name: str
    health: int
    magic: int
    status: str

    def __init__(self, name, health, magic, status):
        self.name = name
        self.health = health
        self.magic = magic
        self.status = status

    def use_skill(self):
        if self.magic > 0:
            print(f"{self.name} 使用了技能")
            self.status = '使用技能'
            self.magic -= 1
        else:
            print("能量不足")
            self.status= "能量耗尽"
    def hearted(self):
        if self.health > 0:
            print(f"{self.name}收到攻击")
            self.status = '收到伤害'
            self.health -= 1
        else:
            self.status = '死'
            print("阵亡")

hero = Hero('蛮王',100,100,"存活")
print(hero.status)
hero.use_skill()
print(hero.status)
hero.hearted()
print(hero.status)
for i in range(100):
    hero.use_skill()
print(hero.status)
for i in range(100):
    hero.hearted()
print(hero.status)

文章来源:https://blog.csdn.net/qq_64746086/article/details/135658122
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。