1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, colour='black', memsize='8G'):
self.brand = brand
self.colour = colour
self.memsize = memsize
def func1(self):
print('%s可以打游戏,写代码,看视频' % self.brand)
c1 = Computer('联想')
print('c1:', c1)
c1.func1()
# 获取
print(c1.colour)
getattr(c1, 'colour')
# 修改
c1.memsize = '16G'
setattr(c1, 'memsize', '16G')
# 添加
c1.price = '$600'
setattr(c1, 'price', '$600')
# 删除
del c1.colour
delattr(c1, 'colour')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建⼈的对⼩小明,让他拥有一条狗大⻩,然后让小明去遛大黄
class Dog:
def __init__(self, name, colour, age):
self.name = name
self.colour = colour
self.age = age
def cry(self):
print('%s在叫唤' % self.name)
class Man:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
print('%s在遛%s' % (self.name, self.dog))
dog1 = Dog('大黄', '黄色', 2)
man1 = Man('小明', 18, dog1.name)
man1.walk_dog()
3.声明一个圆类,自己确定有哪些属性和方法
class Circle:
pi = 3.1415926
def __init__(self, radii, colour, name):
self.radii = radii
self.colour = colour
self.name = name
@classmethod
def func2(cls, radii, name):
area = cls.pi * radii**2
perimeter = 2 * cls.pi * radii
print('%s的面积是%s' % (name, area))
print('%s的周长%s' % (name, perimeter))
yuan1 = Circle(3, 'black', '圆1')
yuan1.func2(yuan1.radii, yuan1.name)
4.创建⼀个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣信息
创建一个班级类:
属性:学⽣,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
import random
class Student:
def __init__(self, name, age=0, study_id='000'):
self.name = name
self.age = age
self.study_id = study_id
self.is_in_class = random.randint(0, 1)
def respond(self):
print('%s,到!' % self.name)
def show(self):
print('姓名:%s 年龄:%d 学号:%s' % (self.name, self.age, self.study_id))
class Class:
def __init__(self, name):
self.students = []
self.name = name
def func():
num = 1
while True:
yield 'stu'+str(num)
num += 1
self.create_id = func()
def add_student(self):
"""添加学生"""
name = input('学生姓名:')
age = int(input('学生的年龄:'))
study_id = next(self.create_id)
stu = Student(name, age, study_id)
self.students.append(stu)
def del_student(self):
"""删除学生"""
del_name = input('请输入要删除的学生的名字:')
flag = False
for stu in self.students[:]:
if stu.name == del_name:
flag = True
stu.show()
value = input('是否删除(y/n):')
if value == 'y':
self.students.remove(stu)
if not flag:
print('没有该学生!')
def call_name(self):
"""点名"""
for stu in self.students:
print(stu.name)
if stu.is_in_class:
stu.respond()
def avg_age(self):
"""求平均年龄"""
ages = 0
for stu in self.students:
ages += stu.age
return ages / len(self.students)
def show_all_students(self):
print('=========%s的学生=========' % self.name)
for stu in self.students:
stu.show()
c1 = Class('py1906')
c2 = Class('py1907')
c1.add_student() # 001
c1.add_student() # 002
c2.add_student() # 001
c1.add_student() # 003
c1.show_all_students()
c2.show_all_students()
print(c1.avg_age())