1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand='hp', color='black', card='1t'):
self.brand = brand
self.color = color
self.card = card
def function(self):
print('功能:打游戏、写代码、看视频')
hp1 = Computer()
hp1.function()
print(hp1.color)
print(getattr(hp1, 'color'))
hp1.card = '200G'
setattr(hp1, 'card', '200G')
hp1.thickness = '10mm'
setattr(hp1, 'thinkness', '10mm')
del hp1.brand
delattr(hp1, 'brand')
2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,然后让⼩小明去遛⼤大⻩黄
class Dog:
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
def call_out(self):
print('%s:汪汪汪' % self.name)
d1 = Dog('小黑', '黑色', '2')
d1.call_out()
class Person:
def __init__(self, name, dog, age=18):
self.name = name
self.age = age
self.dog =dog
def walk_dog(self):
print('%s遛%s' % (self.name, self.dog))
p1 = Person('小明', '大黄')
p1.walk_dog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
import math
class Circle:
def __init__(self, r=2):
self.r = r
def perimeter(self):
print('周长:%s' % (math.pi * 2 * self.r))
def area(self):
print('面积:%s' % (math.pi * self.r ** 2))
c1 = Circle(3)
c1.perimeter()
c1.area()
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
with open('class-1904', 'r', encoding='utf-8') as f:
class_students = eval(f.read())
class Student:
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def sign_in(self):
print('姓名:%s,年龄:%s,学号:%s:' % (self.name, self.age, self.number), '签到')
s1 = Student('小明', '18', '1904004')
s2 = Student('小李', '21', '1904024')
s3 = Student('小刘', '19', '1904011')
class Class:
def __init__(self, class_name, *student):
self.class_name = class_name
self.student_name = student
def student_add(self):
s0 = Student(input('姓名:'), input('年龄:'), input('学号:'))
self.student = s0
class_students[s0.name] = '[s0.age, s0.number]'
# print(eval(class_students['小明'])[0])
with open('class-1904', 'w', encoding='utf-8') as f:
f.write(str(class_students))
def student_del(self):
sx = input('姓名:')
del class_students[sx]
with open('class-1904', 'w', encoding='utf-8') as f:
f.write(str(class_students))
c1 = Class('py1904')
c1.student_add()
# c1.student_del()
print('班级:%s, 姓名:%s, 年龄:%s, 学号:%s' % (c1.class_name, c1.student.name, c1.student.age, c1.student.number)