1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关的方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self,board = 'lenovo',color = 'black'):
self.board = board
self.color = color
def main():
comp1 = Computer()
# 获取
print('品牌:',comp1.board)
print('品牌:',getattr(comp1, 'board', None))
# 添加修改
comp1.game = 'LOL'
print('游戏:',comp1.game)
print('游戏:', setattr(comp1, 'game', None))
# 删除
del comp1.game
if __name__ == '__main__':
main()
2.声明个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Person:
def __init__(self, name='小明', age=18, sex='男', dog: Dog=None):
self.name = name
self.age = age
self.sex = sex
def walk_dog(self):
print('遛狗')
class Dog:
def __init__(self, name='大黄', color = '黄', age = '1'):
self.name = name
self.color = color
def bark(self):
print('wang!wang!wang!')
def main():
p1 = Person()
dog1 = Dog()
print('%s有一条狗狗叫%s' %(p1.name,dog1.name))
print(p1.walk_dog())
if __name__ == '__main__':
main()
3.声明⼀一个圆类:
import math
class Circle:
def __init__(self, r):
self.r = r
def lenth(self):
return math.pi*2*self.r
def area(self):
return math.pi*self.r**2
def main():
c1 = Circle(2)
print('圆的周长是:',c1.lenth())
print('圆的面积是:',c1.area())
if __name__ == '__main__':
main()
结果如下:
圆的周长是: 12.566370614359172
圆的面积是: 12.566370614359172
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
class Student: #定义学生类
def __init__(self,name,school_num,age):
self.name = name
self.school_num = school_num
self.age = age
def show_information(self):
print('姓名:%s 年龄:%s 学号:%s' %(self.name, self.age, self.school_num))
def say_yes(self):
print('到!')
class Classes:
def __init__(self,list, num):
self.num = num
self.list = list
def add_stu(self,student):
self.list.append(student)
def delete_stu(self,student):
self.list.remove(student)
def age_ave(self):
sum = 0
for index in range(len(self.list)):
sum += int(self.list[index].age)
return sum/len(self.list)
def __repr__(self):
s = '['
for index in range(len(self.list)):
s += self.list[index].name +','
s += self.list[index].school_num + ','
s += self.list[index].age + ','
s += ']'
return s
def main():
student1 = Student('小明', '100', '18')
student2 = Student('小红', '101', '19')
student3 = Student('小兰', '102', '20')
student1.show_information()
student2.show_information()
student3.show_information()
student1.say_yes()
class1 = Classes([],'高二1班')
class1.add_stu(student1)
class1.add_stu(student2)
class1.add_stu(student3)
print(class1)
class1.delete_stu(student1)
print(class1)
print(class1.age_ave())
if __name__ == '__main__':
main()
结果如下:
姓名:小明 年龄:18 学号:100
姓名:小红 年龄:19 学号:101
姓名:小兰 年龄:20 学号:102
到!
[小明,100,18,小红,101,19,小兰,102,20,]
[小红,101,19,小兰,102,20,]
19.5