1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
class Computer:
"""声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频"""
def __init__(self, brand, color, ram_size):
self.brand = brand
self.color = color
self.ram_size = ram_size
@staticmethod
def play_game():
print('is playing game...')
@staticmethod
def write_code():
print('is coding...')
@staticmethod
def watch_video():
print('is watching...')
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
c1 = Computer('Lenovo', 'black', '4G')
print(c1.brand, c1.color, c1.ram_size) # Lenovo black 4G
c1.color = 'red'
print(c1.color) # red
c1.price = 7999.0
print(c1.price) # 7999.0
del c1.brand
# print(c1.brand) # AttributeError: 'Computer' object has no attribute 'brand'
b.通过attr相关⽅去获取、修改、添加和删除它的属性
c1 = Computer('Lenovo', 'black', '4G')
print(getattr(c1, 'ram_size')) # 4G
setattr(c1, 'brand', 'Dell')
print(getattr(c1, 'brand')) # Dell
setattr(c1, 'price', 7000.0)
print(c1.price) # 7000.0
delattr(c1, 'price')
# print(c1.price) # AttributeError: 'Computer' object has no attribute 'price'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的⽅法:叫唤
class Dog:
"""狗的属性:名字、颜色、年龄 狗的⽅方法:叫唤 """
def __init__(self, name: str, color: str, age: int):
self.name = name
self.color = color
self.age = age
def bark(self):
print('{} is barking...'.format(self.name))
人的属性:名字、年年龄、狗
人的方法:遛狗
class Person:
"""人的属性:名字、年龄、狗 人的方法:遛狗 """
def __init__(self, name: str, age: int, dog: Dog):
self.name = name
self.age = age
self.dog = dog
def walking_the_dog(self):
print('{} and the dog {} is walking...'.format(self.name, self.dog.name))
a.创建人的对象小明,让他拥有⼀一条狗大黄,然后让⼩明去遛⼤黄
dog1 = Dog('大黄', 'yellow', 3)
p1 = Person('小明', 18, dog1)
# 小明 and the dog 大黄 is walking...
p1.walking_the_dog()
3.声明一个圆类,自己确定有哪些属性和方法
class Circle:
pi = 3.141592653589793
def __init__(self, radius):
self.radius = radius
def get_diameter(self):
"""获得圆的直径"""
return self.radius * 2
def get_perimeter(self):
"""获得圆的周长"""
return 2 * Circle.pi * self.radius
def get_area(self):
"""获得圆的面积"""
return Circle.pi * self.radius * self.radius
示例:
c1 = Circle(10)
print('直径:{}'.format(c1.get_diameter())) # 直径:20
print('周长:{}'.format(c1.get_perimeter())) # 周长:62.83185307179586
print('面积:{}'.format(c1.get_area())) # 面积: 314.1592653589793
4.创建⼀一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
class Student:
"""学生类 属性:姓名,年龄,学号 方法:答到,展示学⽣信息 """
def __init__(self, name: str, age: int, study_id: str):
self.name = name
self.age = age
self.study_id = study_id
def answer(self):
print('This is {}!'.format(self.name))
def __repr__(self):
return 'Student[name = {}, age = {}, study_id = {}]' \
.format(self.name, self.age, self.study_id)
def show_info(self):
print('Student[name = {}, age = {}, study_id = {}]'
.format(self.name, self.age, self.study_id))
创建⼀一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Class:
"""班级类 属性:学生,班级名 方法:添加学生,删除学生,点名, 求班上学生的平均年龄"""
def __init__(self, class_name: str):
self._stu_list = []
self._class_name = class_name
@property
def stu_list(self):
return self._stu_list
@property
def class_name(self):
return self._class_name
@class_name.setter
def class_name(self, value):
self._class_name = str(value)
def add_student(self, stu: Student):
"""添加学生(单个)"""
for index in range(len(self.stu_list)):
if stu.study_id == self.stu_list[index].study_id:
self.stu_list[index] = stu
break
else:
self.stu_list.append(stu)
def add_students(self, stus: list):
"""添加学生(列表)"""
for stu in stus:
self.add_student(stu)
def del_student(self, study_id: str):
"""删除学生(根据学号)"""
for index in range(len(self.stu_list)):
if study_id == self.stu_list[index].study_id:
del self.stu_list[index]
break
else:
print('The student does not exist!')
def roll_call(self):
"""点名"""
print('Start roll call...\n')
stu_len = len(self.stu_list)
for index in range(stu_len):
print(self.stu_list[index].name, end=' ')
if index and index % 3 == 0:
print('\n')
print('There are {} student(s) in the class now.'.format(stu_len))
def avg_age(self):
"""求班上学生的平均年龄"""
return sum(stu.age for stu in self.stu_list) / len(self.stu_list)
def __repr__(self) -> str:
return self.class_name + '\n' + ''.join(str(stu) + '\n' for stu in self.stu_list)
示例:
stu1 = Student('Tim', 18, 'stu001')
stu1.answer() # This is Tim!
stu1.show_info() # Student[name = Tim, age = 18, study_id = stu001]
stu1 = Student('Tim', 18, 'stu001')
stu2 = Student('Jack', 14, 'stu002')
stu3 = Student('Luna', 20, 'stu003')
stu4 = Student('Sansa', 19, 'stu004')
stu5 = Student('Zook', 21, 'stu005')
cls = Class('py1904')
# 添加单个学生
cls.add_student(stu1)
print(cls) # ['Tim']
# 添加学生列表
cls.add_students([stu1, stu2, stu3, stu4, stu5])
print(cls) # ['Tim', 'Jack', 'Luna', 'Sansa', 'Zook']
# 修改学生
stu1.name = 'Tom'
cls.add_student(stu1)
print(cls) # ['Tom', 'Jack', 'Luna', 'Sansa', 'Zook']
# 删除学生
cls.del_student('stu003')
print(cls) # ['Tom', 'Jack', 'Sansa', 'Zook']
# 点名
cls.roll_call()
'''
Tom Jack Sansa Zook
There are 4 student(s) in the class now.
'''
# 求班上学生的平均年龄
print(cls.avg_age()) # 18.0