1.聲明?個電腦類: 屬性:品牌、顏?、內(nèi)存?小 方法:打游戲、寫代碼、看視頻
a.創(chuàng)建電腦類的對象,然后通過對象點的?方式獲取、修改、添加和刪除它的屬性
b.通過attr相關?方法去獲取、修改、添加和刪除它的屬性
class Computer:
def __init__(self, trademark='戴爾', color = '紅色', memory = '8g'):
self.trademark = trademark
self.color = color
self.memory = memory
def play_game(self):
print('打游戲')
def write_code(self):
print('寫代碼')
def look_vide(self):
print('看電視')
computer = Computer()
print(computer.play_game())
print(computer.look_vide())
print(computer.write_code())
#獲取
print(computer.color)
print(getattr(computer, 'color', 'zhl'))
#修改
computer.color = '黃色'
print(computer.color)
setattr(computer, 'memory', '10g')
print(computer.memory)
#添加
computer.color1 = '綠色'
print(computer.color1)
setattr(computer, 'color2', '黑色')
print(computer.color2)
#刪除
del computer.color
print(computer.color)
delattr(computer, 'color')
2.聲明?個人的類和狗的類:
狗的屬性:名字、顏?色、年年齡
狗的?方法:叫喚
人的屬性:名字、年年齡、狗
人的?方法:遛狗
a.創(chuàng)建?人的對象?小明,讓他擁有?一條狗?大?黃,然后讓?小明去遛?大?黃
class Person:
def __init__(self, name, dog, age = '20'):
self.name = name
self.age = age
self.dog = dog
def play_dog(self, color):
print('%s去遛一條%s狗,他的名字叫做%s' %(self.name, color, self.dog))
class Dog:
def __init__(self, name = '大黃', color = '黃色', age = '5'):
self.name = name
self.color = color
self.age = age
def bark(self):
print('狗狗汪汪的叫')
dog1 = Dog()
person = Person('小明', dog1.name)
person.play_dog(dog1.color)
3.聲明?一個矩形類:
屬性:長,寬 方法:計算周長和面
a.創(chuàng)建不同的矩形,并且打印其周長長和面積
class Shape:
def __init__(self,length, width):
self.length = length
self.width = width
def perimeter(self):
return (self.width + self.length) * 2
def area(self):
return self.length * self.width
s1 = Shape(3, 4)
c = s1.perimeter()
area = s1.area()
print(c, area)
4.創(chuàng)建?一個學?生類:
屬性:姓名,年齡,學號
方法:答到,展示學?生信息
創(chuàng)建?一個班級類:
屬性:學?生,班級名
方法:添加學?生,刪除學生,點名, 求班上學生的平均年齡
class Student:
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def answer(self):
print('%s到' %(self.name))
def display(self):
dict1 = {'學生':self.name, '年齡':self.age,'學號':self.number}
return dict1
class Lesson:
def __init__(self, student, class_name):
self.student = student
self.class_name = class_name
def add_student(self, *dict1):
list1 = []
list1.append(dict1)
return list1
def average(self, list1 ):
sum = 0
for i in list1:
for j in i:
sum +=int(j['年齡'])
return sum / (len(list1))
stu1 = Student('周海龍', '20', '001')
stu2 = Student('張程', '10', '002')
stu1.answer()
lesson = Lesson(stu1.name, '1班')
lesson.add_student(stu1.display(), stu2.display())
lesson.add_student(stu1.display(), stu2.display())
print(lesson.add_student(stu1.display(), stu2.display()))
num = lesson.average(lesson.add_student(stu1.display(), stu2.display()))
print(num)