1.聲明?個電腦類: 屬性:品牌靠抑、顏?凛澎、內存?小 方法:打游戲霹肝、寫代碼、看視頻
a.創(chuàng)建電腦類的對象塑煎,然后通過對象點的?方式獲取沫换、修改、添加和刪除它的屬性
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.創(chuàng)建?一個學生類:
屬性:姓名炭晒,年齡待逞,學號
方法:答到,展示學生信息
創(chuàng)建?一個班級類:
屬性:學生网严,班級名
方法:添加學生识樱,刪除學生,點名, 求班上學生的平均年齡
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)