1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
"""类型说明: """
def __init__(self, brand, color, ram):
self.brand = brand
self.color = color
self.ram = ram
def method(self, method):
print(self.brand, method)
computer = Computer('联想', '红色', '8G DDR4 3000Hmz')
computer.method('打游戏')
print(computer.brand)
print('===========attr方法============')
print(getattr(computer, 'brand'))
computer.brand = 'ROG'
print(computer.brand)
print('===========attr方法============')
setattr(computer, 'brand', 'ROG')
print(computer.brand)
computer.ROM = '1T'
print(computer.ROM)
print('===========attr方法============')
setattr(computer, 'DVD', '光驱')
print(computer.DVD)
# del computer.ROM
# print(computer.ROM) AttributeError: 'Computer' object has no attribute 'ROM'
# print('===========attr方法============')
# # delattr(computer, 'DVD')
# print(computer.DVD) AttributeError: 'Computer' object has no attribute 'DVD'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
"""声明人的名字、年龄、狗"""
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def method(self, method='遛'):
print(self.name + method + self.dog)
class Dog:
"""声明狗的名字、颜色、年龄"""
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def method(self, method='汪汪汪'):
print(self.name + method)
person = Person('小米', '22', '哈士奇')
person.method()
print(person)
3.声明一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self):
pass
def method(self, r):
self.perimeter = 2 * math.pi * r
self.area = math.pi * r
a = Circle()
a.method(3)
print(a.perimeter)
print(a.area)
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
import random
all_student = []
class Student:
"""属性:姓名,年龄,学号"""
def __init__(self, name, age, classroom):
self.name = name
self.age = age
self.classroom = classroom
self.dadao = random.randint(0, 1)
all_student.append({'name': self.name, 'age': self.age, 'classroom': self.classroom, 'dadao': self.dadao})
def method(self, name):
for i in all_student:
if i['name'] == name:
if i['dadao'] == True:
print(i, '到')
else:
print(i, '缺勤')
a = Student('刘畅', '19', '001')
b = Student('刘畅1', '29', '002')
a.method('刘畅')
all_class = []
class Classroom:
"""属性:学⽣生,班级名"""
def __init__(self, name, age, class_name):
self.name = name
self.class_name = class_name
self.age = age
self.all_student = []
def stu_add(self, stu):
self.all_student.append(stu)
def stu_del(self, stu_name):
for stu in self.all_student.copy():
if stu.name == stu_name:
self.all_student.remove(stu)
break
def stu_ave(self):
sum1 = 0
for i in self.all_student:
sum1 += i.age
count = len(self.all_student)
average = sum1 / count