- 首页 > it技术 > >
- 声明一个电脑类: 属性:品牌、颜色、内存大小 ;方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
b.通过attr相关的方法去获取、修改、添加和删除它的属性
class Computer:
"""说明文档:电脑类"""
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memorydef play_games(self):
print('打游戏')def write_code(self):
print('写代码')def watch_video(self):
print('看视频')computer1 = Computer('T400', '黑色', '1T')
print('=========对象.的方式============')
# 查
print(computer1.brand)
# 改
computer1.color = '灰色'
print(computer1.color)
# 增
computer1.type = '游戏本'
print(computer1.type)
# 删
del computer1.type
print('=========attr相关的方式============')
# 查
print(getattr(computer1, 'brand', '无'))
# 改
setattr(computer1, 'memory', '2T')
print(computer1.memory)
# 增
setattr(computer1, 'type', '游戏本')
print(computer1.type)
# 删
delattr(computer1, 'type')
# print(computer1.type)
- 声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
"""说明文档:狗类"""
def __init__(self, name, color, age=0):
self.name = name
self.color = color
self.age = agedef bark(self):
print('狗在叫')class Person:
def __init__(self, dog, name, age=18):
self.name = name
self.age = age
self.dog = dogdef walk_the_dog(self):
print(self.name + '去遛' + self.dog)dog1 = Dog('大黄', '黄色', 2)
person1 = Person(dog1.name, '小明')
person1.walk_the_dog()
- 声明?一个圆类,自己确定有哪些属性和方法
import math
# 3.声明?一个圆类,自己确定有哪些属性和方法class Circle:
"""说明文档:圆类"""
def __init__(self, radius):
self.radius = radiusdef circle_area(self):
return self.radius ** 2 * math.pidef circle_perimeter(self):
return self.radius * 2 * math.picircle1 = Circle(4)
print(circle1.circle_area())
print(circle1.circle_perimeter())
- 创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
"""说明文档:学生类"""
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = numberdef answer(self, stu_name):
print(stu_name + '回答:' + '到')def show_stu_info(self):
print('姓名:%s 年龄:%d 学号:%s' % (self.name, self.age, self.number))class ClassAndGrade:
"""说明文档:班级类"""
def __init__(self, class_name):
self.stu_name = []
self.class_name = class_namedef add_stu(self, student):
self.stu_name.append(student)def del_stu(self, student_name):
if not self.stu_name:
print('没有可删除的学生')
for item in self.stu_name:
if item['name'] == student_name:
del item
else:
print('没有找到该学生')def call_the_roll(self):
if not self.stu_name:
print('没有学生')
for item in self.stu_name:
print(item['name'])def avg_age(self):
sum1 = 0
for item in self.stu_name:
sum1 += item['age']
print(sum1/len(self.stu_name))
推荐阅读