1.声明一个电脑类,属性:品牌、颜色、内存大小;方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关方法去获取、修改、添加和删除它的属性。
class Computer:
def __init__(self,band,color,memory):
self.band = band
self.color = color
self.memory = memory
def play_game(self):
print('用%s打游戏' % (self.band))
def write_code(self):
print('用%s写代码' % (self.band))
def watch_video(self):
print('用%s看视频' % (self.band))
2.声明一个人的类和狗的类,狗的属性:名字、颜色、年龄;狗的方法:叫唤;人的属性:名字、年龄、狗;人的方法:遛狗。
a.创建人的对象,小明,让他拥有一条大黄狗,然后让小明去遛大黄狗。
class Dog:
def __init__(self,name,color,age):
self.name = name
self.color = color
self.age = age
def dog_bark(self):
print('%s在叫唤' % (self.name))
class Person:
def __init__(self,name,age,dog):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
return '%s在遛%s' % (self.name, self.dog)
3.声明一个圆类
class Circle:
def __init__(self,radius:int):
self.radius = radius
def area(self):
return 0.25 * (self.radius**2) * 3.14
4.声明一个学生类,属性:姓名、年龄、学号,方法:答到,展示学生信息
创建一个班级类,属性:学生,班级名;方法:添加学生,删除学生,点名,求班上学生的平均年龄。
class Student:
def __init__(self, stu_name, age, id):
self.name = stu_name
self.age = age
self.id = id
def show_stu_info(self):
return self.__dict__
def reply(self):
pass
class The_class:
def __init__(self,class_name,student):
self.class_name = class_name
self.student = student
@staticmethod
def add_stu(*args):
return Student(*args)
@classmethod
def del_stu(cls,*args):
pass
def answer(self):
pass
def average_age(self):
pass
def main():
# 第一题
compuer1 = Computer('戴尔','黑色','256G')
print(compuer1.band, compuer1.color, compuer1.memory)
compuer1.play_game()
compuer1.write_code()
compuer1.watch_video()
print('============================================')
print(compuer1.band) # 获取
compuer1.band = 'Dell' # 修改
print(compuer1.band)
compuer1.name = '小黑' # 添加
print(compuer1.name)
del compuer1.band # 删除
print(compuer1.__dict__)
print('============================================')
print(getattr(compuer1,'band','不存在'))
print(getattr(compuer1,'name','不存在')) # 获取
setattr(compuer1,'name','小红')
print(getattr(compuer1,'name','不存在')) # 修改
setattr(compuer1,'band','Dell') # 添加
print(compuer1.__dict__)
delattr(compuer1,'band')
print(compuer1.__dict__)
print('====================第二题========================')
def main2():
dog1 = Dog('大黄', '黄色', 2)
print(dog1.__dict__)
p1 = Person('小明', 13, dog1.name)
print(str(p1.__dict__)[1:-1])
print(p1.walk_the_dog())
print(('====================第三题========================'))
def main3():
c1 = Circle(20)
print(c1.__dict__)
print(c1.area())
print(('====================第四题========================'))
def main4():
student1 = Student('小明', 13, 1809)
student2 = Student('小王', 15, 1808)
student3 = Student('小红', 17, 1807)
class1 = The_class('第一班',student1)
print(class1.student.name)
if __name__ == '__main__':
main()
main2()
main3()
main4()