1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
- a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
- b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color, rom):
self.brand = brand
self.color = color
self.rom = rom
def games(self, game):
return "可以打" + game
def codes(self, code):
return "可以敲" + code
def video(self, video):
return "可以看" + video
com1 = Computer('联想', '白色', '4G')
print(com1.games('英雄联盟'))
print(com1.codes('python'))
print(com1.video('葫芦娃'))
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
print(com1.brand)
com1.brand = '戴尔'
print(com1.brand)
com1.ram = '400G'
print(com1.ram)
del com1.ram
# print(com1.ram) #AttributeError: 'Computer' object has no attribute 'ram'
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
print(getattr(com1, 'brand'))
setattr(com1, 'brand', '联想')
print(getattr(com1, 'brand'))
setattr(com1, 'ram', '400G')
print(getattr(com1, 'ram'))
delattr(com1, 'ram')
# print(getattr(com1, 'ram')) #AttributeError: 'Computer' object has no attribute 'ram'
2.声明⼀个人的类和狗的类:
- 狗的属性:名字、颜色、年龄
- 狗的方法:叫唤
- 人的属性:名字、年年龄、狗
- 人的方法:遛狗
class Dogs:
def __init__(self, name, color, age=0):
self.name = name
self.color = color
self.age = age
@classmethod
def bark(cls):
return '狗叫'
class Human:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
return self.name+ '遛' + self.dog.name
- a.创建⼈人的对象⼩小明,让他拥有⼀一条狗大黄,然后让小明去遛大⻩
dahuang = Dogs('大黄', '黄色')
xiaoming = Human('小明', 18, dahuang)
print(xiaoming.walk_dog())
3.声明⼀一个圆类,自己确定有哪些属性和方法
from math import pi
class Round:
def __init__(self, radius:float):
self.radius = radius
def area(self):
return '面积:%.2f'% pi*(self.radius**2)
def perimeter(self):
return '周长:%.2f'% (pi*2*self.radius)
print(Round(1).area())
print(Round(1).perimeter())
4.创建⼀一个学⽣生类:
- 属性:姓名,年龄,学号
- 方法:答到,展示学生信息
class Students:
def __init__(self, name:str, number:str, age:int):
self.name = name
self.number = number
self.age = age
def inf(self):
print('姓名:%s 学号:%s' %(self.name, self.number))
def reply(self):
print('%s 到'%self.number)
创建⼀一个班级类:
- 属性:学生,班级名
- 方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Class:
def __init__(self, class_name: str, students=[]):
self.students = students
self.class_name = class_name
def add_stu(self, student):
self.students.append(student)
def del_stu(self,student):
self.students.remove(student)
@classmethod
def call_num(cls, number):
print(number)
def avg_age(self):
age = 0
for student in self.students:
age +=student.age
avg_age = age / len(self.students)
return avg_age
stu1 = Students('小李', '1', 18)
stu2 = Students('小张', '2', 19)
stu3 = Students('小赵', '3', 20)
stu4 = Students('小刘', '4', 21)
cls1 = Class('python1901')
#添加学生
cls1.add_stu(stu1)
cls1.add_stu(stu2)
cls1.add_stu(stu3)
cls1.add_stu(stu4)
print(cls1.students)
for student in cls1.students:
print(student.name)
#删除学生
# cls1.del_stu(stu1)
#
# print(cls1.students[0].name)
#点到
Class.call_num(1)
stu1.reply()
#求班上学生的平均年龄
print(cls1.avg_age())
#展示学生信息
print(stu1.inf())