python面向对象基础练习题

  1. 编写汽车类(颜色,速度)

编写人类(名字,汽车实例)

编写列表 放入三个人, 遍历列表依次打印每个人的信息(包含汽车)创建Rectangle类,

  1. 新建学生类(学号,姓名,年纪)

随机生成10个学生放入列表(年纪随机即可),按学生的年纪对列表中的学生排序

四种方法,并结合装饰器统计四种方法的时间开销

  1. 编写角色类,拥有血量【3000,5000】和攻击力【100,300】

 随机10个角色(血量,攻击力随机)放入列表

 列表中的角色依次攻击下一个(最后一个攻击第一个)

 角色死亡后移除列表,输出最后存活角色信息

  1. 使用面向对象编写 学生管理,持久化存储

输入数字1,添加学生信息(id名字,年纪,性别)

第一个学生id为101 后续学生自动加1

输入数字2,查看所有学生信息

输入数字3,统计学生平均年纪

输入数字4,统计学生性别比例

输入数字0,退出系统

  1. 设计一个继承关系其中存在动物类Animal、狗类Dog和猫类Cat,

对于猫类和狗类都有一个吃eat方法,但是猫和狗的吃eat方法的实现不同,

请合理的设计出Animal Dog Cat

  1. 写出一个类People,并由该类做基类派生出子类Employee和Teacher。

其中People类具有name、age两个成员变量,分别为String类型、整型,

且具有公有的GetAge成员函数,用于返回age变量的值。

Employee类具有成员变量empno,

Teacher类有teacherNo成员变量。

编写show方法可以展示对应实例信息

 ps:参考代码仅代表个人,仅供参考

# 1.编写汽车类(颜色,速度)
# 编写人类(名字,汽车实例)
# 编写列表 放入三个人, 遍历列表依次打印每个人的信息(包含汽车)
# class Car:
#     def __init__(self, color, speed):
#         self.color = color
#         self.speed = speed

#     def __str__(self):
#         return f"汽车颜色{self.color},速度{self.speed}"
#
#
# c1 = Car("红色", 120)
# c2 = Car("白色", 220)
# c3 = Car("黑色", 150)
#
#
# class Person:
#     def __init__(self, name, car):
#         self.name = name
#         self.car = car
#
#     def __str__(self):
#         return f"名字{self.name},{self.car}"
#
#
# p1 = Person("张三", c1)
# print(p1)
# p2 = Person("李四", c2)
# print(p2)
# p3 = Person("王五", c3)
# print(p3)
import random
import time
#
#
# # 2.新建学生类(学号,姓名,年纪)
# # 随机生成10个学生放入列表(年纪随机即可),按学生的年纪对列表中的学生排序
# # 四种方法,并结合装饰器统计四种方法的时间开销
# class Student:
#     def __init__(self, sid, name, age):
#         self.sid = sid
#         self.name = name
#         self.age = age
#
#     def __str__(self):
#         return f"id{self.sid},name{self.name},age{self.age}"
#
#     def get_age(self):
#         return self.age
#
# def time_cost(f):
#     def cala():
#         start = time.time()
#         f()
#         print(f"时间差为{time.time() - start}")
#
#     return cala
#
#
# students = []
# for i in range(100):
#     sid = 101 if not students else students[-1].sid + 1
#     s0 = Student(sid, f"小米{i}", random.randint(1, 300))
#     students.append(s0)
# for s in students:
#     print(s)
#
# print(f"冒泡排序")
#
# @time_cost
# def mao_pao():
#     for i in range(len(students) - 1):
#         for j in range(len(students) - i - 1):
#             if students[j].get_age() < students[j + 1].get_age():
#                 students[j], students[j + 1] = students[j + 1], students[j]
#     for s in students:
#         print(s)
#
#
# mao_pao()
# print(f"选择排序")
#
# @time_cost
# def choice():
#     for i in range(len(students) - 1):
#         max_value = i
#         for j in range(i + 1, len(students)):
#             if students[max_value].get_age() < students[j].get_age():
#                 students[max_value], students[j] = students[j], students[max_value]
#         if max_value != i:
#             print(students)
#     for s in students:
#         print(s)
#
#
# choice()
# print(f"sort排序")
#
# @time_cost
# def sort():
#     students.sort(key=lambda e: e.get_age())
#     for s in students:
#         print(s)
#
#
# sort()
# print(f"sorted排序")
#
# @time_cost
# def sorte():
#     new_list = sorted(students, key=lambda e: e.get_age())
#     for s in new_list:
#         print(s)
#
#
# sorte()
import json
import os.path
import pickle
import random
from os.path import exists

# 3.编写角色类,拥有血量【3000,5000】和攻击力【100,300】
# 随机10个角色(血量,攻击力随机)放入列表
# 列表中的角色依次攻击下一个(最后一个攻击第一个)
# 角色死亡后移除列表,输出最后存活角色信息
class Role:
    def __init__(self, name, blood, attack):
        self.blood = blood
        self.attack = attack
        self.name = name

    def __str__(self):
        return f"name{self.name},hp:{self.blood}nattack:{self.attack}"


rs = [Role(f"name{i}", random.randint(3000, 5000), random.randint(100, 300)) for i in range(10)]
for role in rs:
    print(role)
print(f"战斗开始")
count = 0
while len(rs) > 1:
    for i in range(len(rs) - 1):
        if rs[i].blood > 0:
            rs[i + 1].blood -= rs[i].attack
    if rs[-1].blood > 0:
        rs[0].blood -= rs[-1].attack
    for i in range(len(rs)-1 , -1, -1):
        if rs[i].blood <= 0:
            rs.remove(rs[i])
    count += 1
    print(f"第{count}轮结束")
    for r in rs:
        print(r)

print(f"战斗完毕")
print(f"{rs[0]}")

import random
# 4.使用面向对象编写 学生管理,持久化存储
# 输入数字1,添加学生信息(id名字,年纪,性别)
# 第一个学生id为101 后续学生自动加1
# 输入数字2,查看所有学生信息
# 输入数字3,统计学生平均年纪
# 输入数字4,统计学生性别比例
# 输入数字0,退出系统
# class Student:
#     def __init__(self, id, name, age, sex):
#         self.id = id
#         self.name = name
#         self.age = age
#         self.sex = sex
#
#     def __str__(self):
#         return f"id{self.id},name{self.name},age{self.age},sex{self.sex}"
#
#
# class StudentManage:
#     def __init__(self):
#         self.students = []
#
#     def add_name(self):
#         while True:
#             name = input("请输入姓名")
#             if 2 <= len(name) <= 4:
#                 return name
#             else:
#                 print(f"输入不合法,重新输入")
#
#     def add_age(self):
#         while True:
#             age = int(input("请输入年龄"))
#             if 2 <= age <= 84:
#                 return age
#             else:
#                 print(f"输入不合法,重新输入")
#
#     def add_sex(self):
#         while True:
#             sex = input("请输入性别")
#             if sex in ["男", "女"]:
#                 return sex
#             else:
#                 print(f"输入不合法,重新输入")
#
#     def continue_quit(self):
#         while True:
#             option2 = input("继续(Y)退出(N)")
#             if option2 not in ["y", "Y", "n", "N"]:
#                 print(f"输入不合法")
#             elif option2 == "y" or option2 == "y":
#                 return option2
#             elif option2 == "n" or option2 == "N":
#                 return option2
#
#     def add_student(self):
#         while True:
#             sid = 101 if not self.students else self.students[-1].id + 1
#             name = self.add_name()
#             age = self.add_age()
#             sex = self.add_sex()
#             s0 = Student(sid, name, age, sex)
#             self.students.append(s0)
#             print(f"添加成功!")
#             option2 = self.continue_quit()
#             if option2 == "y" or option2 == "Y":
#                 pass
#             if option2 == "n" or option2 == "N":
#                 break
#
#     def show_all(self):
#         if self.students:
#             for s in self.students:
#                 print(s)
#         else:
#             print(f"还未添加学生")
#
#     def get_avg(self):
#         if self.students:
#             total = 0
#             for s in self.students:
#                 total += s.age
#                 print(f"平均年龄:{total / len(self.students)}")
#         else:
#             print(f"还未添加学生")
#
#     def get_rate(self):
#         if self.students:
#             man_count = 0
#             women_count = 0
#             for s1 in self.students:
#                 if s1.sex == "男":
#                     man_count += 1
#                 else:
#                     women_count += 1
#             print(f"男生占比{man_count / len(self.students)}女生占比{women_count / len(self.students)}")
#         else:
#             print(f"还未添加学生")
#
#
# class SystemManage:
#
#     def __init__(self):
#         self.sm = StudentManage()
#
#     def main_menu(self):
#         menu = """输入数字1,添加学生信息(id名字,年纪,性别)
#     第一个学生id为101 后续学生自动加1
#     输入数字2,查看所有学生信息
#     输入数字3,统计学生平均年纪
#     输入数字4,统计学生性别比例
#     输入数字0,退出系统"""
#         print(f"{menu}")
#
#     def get_option(self):
#         while True:
#             option = input("请输入选项")
#             if option not in [str(i) for i in range(0, 5)]:
#                 print(f"输入不合法")
#             else:
#                 return option
#
#     def run(self):
#         while True:
#             self.main_menu()
#             main = self.get_option()
#             if main == "0":
#                 break
#             elif main == "1":
#                 self.sm.add_student()
#             elif main == "2":
#                 self.sm.show_all()
#             elif main == "3":
#                 self.sm.get_avg()
#             elif main == "4":
#                 self.sm.get_rate()
#
#
# if __name__ == '__main__':
#     system_manage = SystemManage()
#     system_manage.run()

# 5.设计一个继承关系其中存在动物类Animal、狗类Dog和猫类Cat,
# 对于猫类和狗类都有一个吃eat方法,但是猫和狗的吃eat方法的实现不同,
# 请合理的设计出Animal Dog Cat

# class Animal:
#     def __init__(self, name, eat):
#         self.eat = eat
#         self.name = name
#
#     def __str__(self):
#         return f"{self.name}{self.eat}"
#
#
# a = Animal("动物", "进食")
# print(a)
#
#
# class Dog(Animal):
#     def __init__(self, name, eat):
#         super().__init__(name, eat)
#
#     def walk(self):
#         return "走路摇尾巴"
#
#
# d = Dog("小花狗", "大口大口吃")
# print(d)
# print(d.walk())
#
#
# class Cat(Animal):
#     def __init__(self, name, eat):
#         super().__init__(name, eat)
#
#     def walk(self):
#         return "上蹿下跳"
#
#
# c = Cat("小花猫", "小口小口吃")
# print(c)
# print(c.walk())


# 6.写出一个类People,并由该类做基类派生出子类Employee和Teacher。
# 其中People类具有name、age两个成员变量,分别为String类型、整型,
# 且具有公有的GetAge成员函数,用于返回age变量的值。
# Employee类具有成员变量empno,
# Teacher类有teacherNo成员变量。
# 编写show方法可以展示对应实例信息

class People:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def __str__(self):
        return f"name:{self.name},age:{self.age}"

    def get_age(self):
        return self.age

    def show(self):
        return self.__str__()


p0 = People("张三", 20)
print(p0.show())
print(p0.get_age())


class Employee(People):
    def __init__(self, name, age, money, empno):
        self.money = money
        self.empno = empno
        super().__init__(name, age)

    def __str__(self):
        return f"{super().__str__()},money:{self.money},empno:{self.empno}"

    def show(self):
        return "乾坤未定,你我皆牛马"


e0 = Employee("李四", 23, 10000, 101)
print(e0)
print(e0.show())


class Teacher(Employee):
    def __init__(self, name, age, money, empno, teacherno):
        self.techerno = teacherno
        super().__init__(name, age, money, empno)

    def __str__(self):
        return f"{super().__str__()},teacherno:{self.techerno}"

    def show(self):
        return "人民教师"


t0 = Teacher("张芸芸", 18, 5000, "语文", 101)
print(t0)
print(t0.show())

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值