1.声明⼀个电脑类: 属性:品牌、颜⾊、内存⼤小 方法:打游戏、写代码、看视频
a.创建电脑类的对象,然后通过对象点的⽅方式获取、修改、添加和删除它的属性
b.通过attr相关⽅方法去获取、修改、添加和删除它的属性
class Human:
def __init__(self, name='Kiin', age=20, dog=None):
self.name = name
self.age = age
self.dog = dog
def take_the_dog(self):
if self.dog:
return '{}在遛{}'.format(self.name, self.dog.name)
else:
return '没有狗'
class Dog:
def __init__(self, name='Khan', color='black', age=2):
self.name = name
self.age = age
self.color = color
def Bark(self):
print('%s在汪汪汪地叫' % self.name)
dog = Dog('大黄')
man = Human('小小明')
man.dog = dog
print(man.take_the_dog())
3.声明一个圆类,自己确定有哪些属性和方法
class Point:
def __init__(self, x, y):
self.x = x
self.y = y
def distance(self, other):
a = self.x - other.x
b = self.y - other.y
return (a**2 + b**2)**0.5
class Circle:
pi = 3.1415926
def __init__(self, rad, center):
self.rad = rad
self.center = center
def area(self):
return Circle.pi * self.rad ** 2
def perimeter(self):
return 2 * Circle.pi * self.rad
def is_intersect(self, other):
"""两个圆是否相交"""
distance = self.center.distance(other.center)
if distance >= self.rad + other.rad:
return False
return True
4.创建⼀一个学生类:
属性:姓名,年龄,学号
方法:答到,展示学生信息
创建⼀一个班级类:
属性:学生,班级名
方法:添加学生,删除学生,点名, 求班上学生的平均年龄
class Student:
student_all = []
name_all = []
age_all = []
number_all = []
def __init__(self, name='Kiin', age=20, number='040'):
self.name = name
self.age = age
self.number = number
def count_all(self):
Student.name_all.append(self.name)
Student.age_all.append(self.age)
Student.number_all.append(self.number)
Student.student_all.append([self.name, self.age, self.number])
return Student.student_all
def answer(self, name):
if name in Student.name_all:
return True
else:
return False
def display(self):
return self.name, self.age, self.number
class Classroom:
student = Student.name_all
classroom_name = 'python1904'
def add_student(self, student2):
Classroom.student.append(student2)
return Classroom.student
def del_student(self,student2):
Classroom.student.remove(student2)
return Classroom.student
def call_student(self,name):
if name in Classroom.student:
return True
else:
return False
def count_age(self):
n = 0
for x in Student.age_all:
n += x
return n/len(Student.age_all)
class1 = Classroom()
student1 = Student('小明', 20, '250')
student2 = Student('小强', 22, '260')
student1.count_all()
print(student2.count_all())
print(student1.answer('小明'))
print(class1.add_student('小花'))
print(class1.del_student('小花'))
print(class1.call_student('小花'))
print(class1.count_age)