1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,types,color,internal = '256GB'):
self.types = types
self.color = color
self.internal = internal
def play_game(self):
print('play_game')
def write_code(self):
print('write code')
def see_film(self):
print('see film')
computer = Computer('Lenovo','black')
print(computer.types,computer.color,computer.internal)
computer.types = 'ASUS'
computer.color = 'blue'
computer.internal = '512GB'
computer.size = '16英寸'
del computer.types
print(getattr(computer,'color'))
print(setattr(computer,'color','green'))
print(setattr(computer,'types','Lenovo'))
delattr(computer,'types')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
class Person:
def __init__(self,name,age,dog):
self.name =name
self.age =age
self.dog =dog
def walk_dog(self):
if self.dog:
print('%s遛%s'%(self.name,self.dog.name))
else:
print('你还是只单身狗')
class Dog:
def __init__(self,name,color,age):
self.name =name
self.color =color
self.age = age
def call_out(self):
print('%s叫唤'%self.name)
dog1 = Dog('小小','white',3)
person1= Person('习**','40',dog1)
person1.walk_dog()
dog1.call_out()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
pi = 3.141592653
def __init__(self,radius):
self.radius = radius
def area(self):
return (Circle.pi*self.radius**2)
def perimeter(self):
return (2*Cricle.pi*self.radius)
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student:
dict1 ={}
def __init__(self,name,age,code):
self.name = name
self.age = age
self.code = code
Student.dict1['name'] =name
Student.dict1['age'] = age
Student.dict1['code'] = code
def daying(self):
print('到!!name:%s,age:%scode:%s'%(self.name,self.age,self.code))
class Class:
dict2 = {}
table = []
def __init__(self,student,classs):
self.student =student
self.classs = classs
#
def add_stu(self):
if self.classs not in Class.dict2.keys():
Class.table=[]
a = self.student.copy()
Class.table.append(a)
Class.dict2[self.classs] = Class.table
print(Class.dict2)
#
def del_stu(self,code,classs):
for i in Class.dict2[classs]:
if i['code']==code:
del i
#
def ask(self,code):
for i in Class.dict2[self.classs]:
if i['code']==code:
c = Student(i['name'],i['age'],i['code'])
c.daying()
def average(self):
a =0
for i in Class.dict2[self.classs]:
a+=int(i['age'])
b = a //len(Class.dict2[self.classs])
print(b)
s1=Student('小明','12','001')
c1=Class(s1.dict1,'classs1')
c1.add_stu()
s2 =Student('小花','16','002')
c1.ask('001')
c1.add_stu()
c1.average()