1.声明一个电脑类: 属性:品牌、颜色、内存大小 方法:打游戏、写代码、看视频
class Computer:
def __init__(self, brand, color, memory, ):
self.brand = brand
self.color = color
self.memory = memory
def game(self):
return '用%s的电脑打游戏' % self.brand
def code(self):
return '用%s的电脑写代码' % self.brand
def video(self):
return '用%s的电脑看视频' % self.brand
a.创建电脑类的对象,然后通过对象点的方式获取、修改、添加和删除它的属性
com1 = Computer('联想', '红色', '8GB')
print(com1.color)
com1.color = '黑色'
print(com1.color)
com1.cpu = 'i5'
print(com1.cpu)
del com1.brand
b.通过attr相关方法去获取、修改、添加和删除它的属性
com2 = Computer('苹果', '灰色', '4GB')
print(getattr(com2, 'color'))
setattr(com2, 'color', '白色')
print(getattr(com2, 'color'))
setattr(com2, 'cpu', 'os')
print(getattr(com2, 'cpu'))
delattr(com2, 'memory')
2.声明一个人的类和狗的类:
狗的属性:名字、颜色、年龄
狗的方法:叫唤
人的属性:名字、年龄、狗
人的方法:遛狗
a.创建人的对象小明,让他拥有一条狗大黄,然后让小明去遛大黄
class Dog:
def __init__(self, name1, color, age1):
self.name = name1
self.color = color
self.age = age1
@staticmethod
def bark():
print('叫唤')
class Person:
def __init__(self, name2, age2, dog):
self.name = name2
self.age = age2
self.dog = dog
def walkTheDog(self):
print('%s遛%s' % (self.name, self.dog))
dog1 = Dog('大黄', '黄色', 3)
person1 = Person('小明', 23, dog1.name)
person1.walkTheDog()
3.声明一个圆类,自己确定有哪些属性和方法
import math
n = math.pi
class Circle:
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * n * self.radius
def area(self):
return n * (self.radius ** 2)
4.创建一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学⽣生信息
创建一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
def __init__(self, name, age, num):
self.name = name
self.age = age
self.num = num
def class_name(self):
print('到,我叫%s,年龄%d岁,学号%d'%(self.name,self.age,self.num))
def dict1(self):
dict1 = {'姓名':self.name,'年龄':self.age,'学号':self.num}
return dict1
stu1 = Student('小明',17,23)
stu1.class_name()
stu2 = Student('小红',18,24)
stu3 = Student('小聪',20,45)
class Class:
def __init__(self,list1=[],class_name='一班'):
self.student = list1
self.class_name = class_name
def add_stu(self,student):
"""添加学生"""
self.student.append(student)
print(self.student)
def delete(self,student):
self.student.remove(student)
print(self.student)
def call_name(self):
for item in self.student:
print(item['姓名'])
def v_age(self):
count = 0
sum = 0
for item in self.student:
sum += item['年龄']
count+=1
print(sum/count)
c1 = Class([stu1.dict1()])
c1.add_stu(stu2.dict1())
c1.add_stu(stu3.dict1())
c1.v_age()