1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
class Pc:
"""电脑"""
def __init__(self, brand, colour, memory):
self.brand = brand
self.colour = colour
self.memory = memory
def game(self):
pass
def code(self):
pass
def video(self):
pass
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
p = Pc('Thunderobot', '银色', '8g') # 创建
print(p.colour) # 查询
p.colour = '黑色' # 修改
p.weight = '5kg' # 添加
del p.weight # 添加
b.通过attr相关方法去获取、修改、添加和删除它的属性
print(getattr(p, 'colour')) # 查询
setattr(p, 'colour', '银色') # 修改
setattr(p, 'weight', '5kg') # 添加
del p.weight # 删除
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
class Dog:
"""狗"""
def __init__(self, name='unknow', colour='unknow', age='unknow'):
self.dog_name = name
self.dog_colour = colour
self.dog_age = age
def barking(self):
print(self.dog_name, ':“汪汪汪!”')
return
人的属性:名字、年龄、狗
人的方法:遛狗
class Person(Dog):
"""人"""
def __init__(self, name, age, dog_name='unknow', dog_colour='unknow', dog_age='unknow'):
Dog.__init__(self, dog_name, dog_colour, dog_age)
self.name = name
self.age = age
def walk_dog(self):
print('%s出门溜%s' % (self.name, self.dog_name))
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
person = Person('小明', '20', '大黄')
person.walk_dog()
3.声明一个圆类,自己确定有哪些属性和方法
import math
class Round:
def __init__(self, radius: float):
self.radius = radius
def area(self):
return self.radius * self.radius * math.pi
def girth(self):
return 2 * math.pi * self.radius
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
student = [{'姓名': '小明', '年龄': 18, '学号': '1'}]
class Student:
def __init__(self, name, age):
self.stu_name = name
self.stu_age = age
self.stu_id = str(len(students) + 1)
students.append({'姓名': name, '年龄': age, '学号': self.stu_id})
def say_yes(self):
print(self.stu_name, ':“到!”')
def ex_stu(self):
print(self.stu_name, self.stu_age, self.stu_id)
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
students = [{'姓名': '小明', '年龄': 18, '学号': '1'}]
class Classes:
def __init__(self, class_name):
self.class_name = class_name
self.students = students
def add_stu(self, stu_name, stu_age: int):
student = {'姓名': stu_name, '年龄': stu_age, '学号': str(len(students) + 1)}
students.append(student)
print('添加成功')
def del_stu(self, stu_name='', stu_id=''):
for stu_dic in students:
if stu_name == stu_dic['姓名'] or stu_id == stu_dic['学号']:
students.remove(stu_dic)
print('删除成功')
def say_yes(self, stu_name='', stu_id=''):
for stu_dic in students:
if stu_name == stu_dic['姓名'] or stu_id == stu_dic['学号']:
print('Yes!')
def ave_age(self):
ages = 0
for stu_dic in students:
ages += stu_dic['年龄']
return ages / len(students)