1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Computer:
def __init__(self, brand, color, memsize):
self.brand = brand
self.color = color
self.memsize = memsize
def info(self):
print(self.brand, self.color, self.memsize)
def paly_game(self):
print('打游戏')
def write_code(self):
print('写代码')
def watch_tv(self):
print('看视频')
user1 = Computer('Dell', 'black', '8G')
user2 = Computer('hp', 'white', '16G')
user1.cpu = 'i7'
print(user1.cpu) # i7
user1.memsize = '16G'
print(user1.memsize) # 16G
del user2.color
# print(user2.color) # AttributeError: 'Computer' object has no attribute 'color'
setattr(user1, 'price', 7500)
print(user1.price) # 7500
setattr(user2, 'memsize', '32G')
print(user2.memsize) # 32G
# delattr(user2, 'color')
# print(user2.color) # AttributeError: color
###2.声明⼀个人的类和狗的类:
狗的属性:名字、颜⾊色、年年龄
狗的⽅方法:叫唤
人的属性:名字、年年龄、狗
人的⽅方法:遛狗
a.创建⼈人的对象⼩小明,让他拥有⼀一条狗⼤大⻩黄,
然后让⼩小明去遛⼤大⻩黄
"""
class Person:
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
print('%s在遛%s' % (people.name, self.dog.name))
class Dog:
def __init__(self, name, color, age, ):
self.name = name
self.color = color
self.age = age
def cry(self):
print('%s:汪汪往' % self.name)
dog1 = Dog('旺财', 'black', '5')
dog2 = Dog('来福', 'black', '5')
dog = dog2
people = Person('小明', '25', dog)
people.walk_dog()
3.声明⼀一个圆类,自己确定有哪些属性和方法
class Circle:
def __init__(self, r):
self.r = r
def area(self):
return self.r**2*3.14
def perimeter(self):
return 2*3.14*self.r
4.创建⼀一个学⽣生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建⼀一个班级类:
属性:学⽣生,班级名
方法:添加学⽣生,删除学生,点名, 求班上学生的平均年龄
"""
class Student:
def __init__(self, name, age, stu_id):
self.name = name
self.age = age
self.stu_id = stu_id
def rollcall(self):
print('%s:到!' % self.name)
def stu_info(self):
print('学生信息:', self.name, self.age, self.stu_id)
class Classroom:
def __init__(self, stu1, classinfo):
self.stu = stu1
self.classinfo = classinfo
def addstu(self):
stu1.name = ???
stu1.age = ???
stu1.stu_id = ???
# setattr(stu1, 'name')
# setattr(stu1, 'age')
# setattr(stu1, 'stu_id')
def del_stu(self):
del stu1.???
del stu1.???
del stu1.???
def age_average(self):
count = 0
average = 0
for i in str(stu1.age):
count += i
average = count / int(i)
print('班级年龄平均值为:%s' % average )
def rollcall(self):
print('%s:到!' % self.stu.name)
stu1 = Student('田宇', '24', 'py1904008')
stu2 = Classroom(stu1, 'py1904')