import math
1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
class Computer:
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play(self):
print('play game')
def write(self):
print('write code!')
def watch(self):
print('watch avi!')
c1 = Computer('联想', 'black', '16G')
# a.方法
print(c1.color)
c1.memory = '32G'
c1.cpu = 'i9-9900k'
del c1.color
print(c1.brand, c1.memory, c1.cpu)
# b.attr方式
print(getattr(c1, 'cpu', 'i7-8700'))
setattr(c1, 'memory', '64G')
setattr(c1, 'VGA', 'TITAN RTX')
delattr(c1, 'brand')
print(c1.cpu, c1.VGA, c1.memory)
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self, dogname, color='black', dogage=1):
self.dogname = dogname
self.color = color
self.dogage = dogage
def shout(self):
print('汪汪汪!')
class Person:
def __init__(self, name, dog:Dog=None, age=22):
self.name = name
self.age = age
self.dog = dog
def stroll(self):
if self.dog:
print('%s正在遛%s' % (self.name, self.dog))
else:
print('没有狗!遛自己')
p2 = Dog('大黄')
p1 = Person('小明', p2.dog)
p1.stroll()
3.声明一个圆类
import math
class circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def peri(self):
return math.pi * self.radius * 2
4.创建一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
class student:
def __init__(self, name, age=12, id='1001'):
self.name = name
self.age = age
self.id = id
def answ(self, name):
print('%s到!' % name)
def show(self, name, age, id):
print('姓名:%s,年龄:%d,学号:%s' % (name, age, id))
def __repr__(self):
return '姓名:%s,年龄:%d,学号:%s' % (self.name, self.age, self.id)
s1 = student('小明')
s1.answ(s1.name)
s1.show(s1.name, s1.age, s1.id)
5.创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class CLASS:
students = []
def __init__(self, clasnum):
self.clasnum = clasnum
def addstu(self, student):
self.students.append(student.__dict__)
def del_stu(self, student):
self.students.__delattr__(student)
def call(self, student):
print(student)
def aveg(self, students):
sum = 0
for i in students:
sum += i['age']
return sum / len(students)
s2 = student('小u', 13)
s3 = student('小hong', 14)
s4 = student('gang', 32)
C1 = CLASS(1)
C1.addstu(s2)
C1.addstu(s3)
C1.addstu(s4)
C1.call(s2.name)
print(C1.aveg(C1.students))