1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,brand,color,memory):
self.brand=brand
self.color=color
self.memory=memory
def play_game(self):
return '打游戏'
def write_code(self):
return '写代码'
def see_video(self):
return '看视屏'
computer1=Computer('联想','红色','8_+128g')
computer2=Computer('三星','黑色','8+128g')
print(computer1.play_game())
print(computer1.write_code())
print(computer1.see_video())
获取属性
print(computer1.brand,computer1.color,computer1.memory)#联想 红色 8_+128g
修改属性
computer1.brand='华硕'
computer1.color='白色'
computer1.memory='4+86g'
print(computer1.brand,computer1.color,computer1.memory)#华硕 白色 4+86g
添加属性
computer1.system='win10'
print(computer1.brand,computer1.color,computer1.memory,computer1.system)#华硕 白色 4+86g win10
删除属性
del computer1.system
print(computer1.system) AttributeError: 'Computer' object has no attribute 'system'
attr方式查增删改
获取
print(getattr(computer2,'brand'))#三星
print(getattr(computer2,'color'))#黑色
print(getattr(computer2,'memory'))#8+128g
print(getattr(computer2,'system','win8')) #没有system属性,返回默认值win8
增改
setattr(computer2,'brand','apple')
setattr(computer2,'color','白色')
setattr(computer2,'memory','8+256g')
setattr(computer2,'system','不知道苹果操作系统')
setattr(computer2,'price','12888rmb') #没有price属性,添加price属性
print(computer2.brand,computer2.color,computer2.memory,computer2.system,computer2.price)
apple 白色 8+256g 不知道苹果操作系统 12888rmb
删除
delattr(computer2,'system')
print(computer2.system) #AttributeError: 'Computer' object has no attribute 'system'
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Dog:
def __init__(self,name,color,age):
self.name=name
self.color=color
self.age=age
def dog_bark(self):
return '汪汪汪'
dog1=Dog('李福贵','黄色','2')
print(dog1.dog_bark())
class Person:
def __init__(self,name1,age,pet=''):
self.name=name1
self.age=age
self.pet=dog1.name
def walk_the_dog(self):
return '%s在公园遛%s'%(person1.name,person1.pet)
person1=Person('小钢炮','22')
print(person1.walk_the_dog())
3.声明⼀一个圆类:
class Circle:
def __init__(self,radius):
self.radius=radius
def area(self):
return 3.14*self.radius**2
def peri(self):
return 2*3.14*self.radius
circle1=Circle(3)
print(circle1.area())
print(circle1.peri())
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student(object):
def __init__(self,name,age,study_id):
self.name=name
self.age=age
self.study_id=study_id
def replay(self):
print('%s,到'%self.name)
def show_info(self):
print(self.name,self.age,self.tudy_id)
class Class():
def __init__(self,name:str):
self.name=name
self.students=[ ]
self.__creat_id= self.name+str(x).rjust(3,'0') for x in range(1,101)
def add_student(self):
name=input('姓名')
age=int(input('年龄'))
study_id=next(self.__creat_id)
stu1=Student(name,age,study_id)
self.students.append(stu1)
网友评论