"""------ author == 李 墨 ------"""
import math
import random
random.seed(0)
1
class Computer:
def __init__(self,brand='thinkpad',color='black',memory='8G'):
self.brand=brand
self.color=color
self.memory=memory
def play_game(self):
print('打游戏')
def coding(self):
print('写代码')
def watch_TV(self):
print('看视频')
a
cp1=Computer()
print(cp1.color)
cp1.memory='16G'
print(cp1.memory)
cp1.weight='2kg'
print(cp1.__dict__)
del cp1.color
print(cp1.__dict__)
# print(cp1.color)AttributeError: 'Computer' object has no attribute 'color'
b
cp2=Computer()
print(getattr(cp2,'color'))
setattr(cp2,'memory','16G')
print(cp2.memory)
setattr(cp2,'weight','2kg')
print(cp2.weight)
delattr(cp2,'color')
print(cp2.__dict__)
2
class Dog:
def __init__(self,name,color,age):
self.name=name
self.color=color
self.age=age
def bark(self):
print('%s快过来!')
dog1=Dog('大黄','yellow',2)
class Human:
def __init__(self,name,age):
self.name=name
self.age=age
def walk_a_dog(self,dog1):
print('%s遛%s'%(self.name,dog1.name))
a
hm1=Human('小明','18')
hm1.walk_a_dog(dog1)
3
class Circular:
def __init__(self,radius):
self.radius=radius
def girth(self):#周长
return 2*math.pi*self.radius
def measure(self):
return math.pi*(self.radius**2)
c1=Circular(10)
print(c1.girth(),c1.measure())
4
class Student:
def __init__(self,name,age,stuid):
self.name=name
self.age=age
self.stuid=stuid
self.exist=random.randint(0,1)
def answer(self):
if self.exist:
print('%s到'%self.name)
else:
print('%s未到'%self.name)
def showStuData(self):
print('学生:%s,年龄:%s,学号:%s,是否上课:%s'%(self.name,self.age,self.stuid,self.exist))
# return {'姓名':self.name,'学号':self.stuid,'年龄':self.age}
allid=(str(i).zfill(3) for i in range(1,50))
allname=(chr(i) for i in range(ord('a'),ord('z')))
all_stu=[]
for i in range(20):#20个学生
stu=Student(next(allname),random.randint(14,24),next(allid))
stu.answer()
stu.showStuData()
all_stu.append(stu)
print('==============分割线================')
class ClassData:
def __init__(self,className='py1902',stu_data=[]):
self.stu=stu_data
self.name=className
def addStu(self,stu1):
self.stu.append(stu1)
def delStu(self,name1):
self.stu=list(item for item in self.stu if item.name!=name1)
def callStu(self):
for item in self.stu:
if item.exist:
print('%s到;'%item.name,end='')
else:
print('%s未到;'%item.name,end='')
print()
def aveAge(self):
list_age=list(iter.age for iter in self.stu)
return sum(list_age) / len(list_age)
class1=ClassData(stu_data=all_stu)
stu_add=Student('添加者',18,next(allid))
class1.addStu(stu_add)
class1.delStu('b')
class1.callStu()
print('平均年龄:',class1.aveAge())