1.聲明?個電腦類: 屬性:品牌、顏?、內(nèi)存?小 方法:打游戲、寫代碼、看視頻
a.創(chuàng)建電腦類的對象,然后通過對象點的?方式獲取、修改、添加和刪除它的屬性
b.通過attr相關(guān)?方法去獲取、修改、添加和刪除它的屬性
class Computer:
def __init__(self, brand, color, memory_size):
self.brand = brand
self.color = color
self.memory_size = memory_size
def play_game(self):
print('打游戲')
def write_code(self):
print('敲代碼')
def watch_tv(self):
print('看電視')
# a.
c1 = Computer('lenovo', 'black', '500G')
print(c1.brand) # lenovo
c1.color = 'white'
c1.type = 'Thinkpad'
print(c1.color, c1.type) # white Thinkpad
del c1.type
# print(c1.type) # AttributeError: 'Computer' object has no attribute 'type'
# b.
print(getattr(c1, 'brand')) # lenovo
setattr(c1, 'color', 'white')
setattr(c1, 'type', 'Thinkpad')
print(c1.color, c1.type) # white Thinkpad
delattr(c1, 'type')
# print(c1.type) # AttributeError: 'Computer' object has no attribute 'type'
2.聲明?個人的類和狗的類:
狗的屬性:名字、顏?色、年年齡
狗的?方法:叫喚
人的屬性:名字、年年齡、狗
人的?方法:遛狗
a.創(chuàng)建?人的對象?小明,讓他擁有?一條狗?大?黃,然后讓?小明去遛?大?黃
class Person:
"""
人的一個類
name:人的姓名
age:人的年齡
dog:人的狗
"""
__slots__ = ('name', 'age', 'dog')
def __init__(self, name, age, dog):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
print('%s溜他的%s' % (self.name, self.dog.name))
class Dog:
"""
狗的一個類
name: 狗的名字
age: 狗的年齡
color:狗的顏色
"""
__slots__ = ('name', 'age', 'color')
def __init__(self, name, color, age):
self.name = name
self.age = age
self.color = color
def call_out(self):
print('%s,汪汪汪' % self.name)
dog1 = Dog('大黃', '黃色', 2)
p1 = Person('小明', 18, dog1)
p1.walk_the_dog()
print(p1.dog.age)
3.聲明?一個圓類,自己確定有哪些屬性和方法
from math import pi
class Circle:
"""
圓的一個類
radius:半徑
area:求圓的面積
perimeter:求圓的周長
"""
def __init__(self, radius):
self.radius = radius
def area(self):
return pi*self.radius**2
def perimeter(self):
return 2*pi*self.radius
circle1 = Circle(5)
print(circle1.area())
print(circle1.perimeter())
4.創(chuàng)建?一個學(xué)?生類:
屬性:姓名,年齡,學(xué)號
方法:答到,展示學(xué)?生信息
創(chuàng)建?一個班級類:
屬性:學(xué)?生,班級名
方法:添加學(xué)?生,刪除學(xué)生,點名, 求班上學(xué)生的平均年齡
class Student:
__slots__ = ('name', 'age', 'study_id')
def __init__(self, name, age, study_id):
self.name = name
self.age = age
self.study_id = study_id
def massage(self):
print('到,我叫%s,今年%d歲,學(xué)號是%s' % (self.name, self.age, self.study_id))
class Class:
def __init__(self, class_name, *students):
self.name = class_name
self.students = list(students)
def add_student(self, student): # 添加學(xué)生
self.students.append(student)
return
def del_student(self, student): # 刪除學(xué)生
self.students.remove(student)
def call_the_roll(self): # 點名
for student in self.students:
print(student.name)
return
def ave_age(self): # 平均年齡
sum_age = 0
for student in self.students:
sum_age += student.age
return sum_age/len(self.students)
if __name__ == '__main__':
s1 = Student('小明', 18, '001')
s2 = Student('小畫', 13, '002')
s3 = Student('小度', 21, '003')
class1 = Class('py1904', s1)
class1.add_student(s2)
class1.add_student(s3)
class1.add_student(Person('小張', 17, '004'))
class1.call_the_roll()
print(class1.ave_age())