"""author = Zard"""
1.聲明?個(gè)電腦類: 屬性:品牌椰苟、顏?、內(nèi)存?小 方法:打游戲碌更、寫代碼裕偿、看視頻
a.創(chuàng)建電腦類的對(duì)象,然后通過對(duì)象點(diǎn)的方式獲取痛单、修改嘿棘、添加和刪除它的屬性
b.通過attr相關(guān)?方法去獲取、修改旭绒、添加和刪除它的
class Computer:
"""電腦類"""
def __init__(self,brand,color,ram):
self.brand = brand
self.color = color
self.ram = ram
def play_game(self):
print('打游戲')
def write_code(self):
print('寫代碼')
def watch_video(self):
print('看視頻')
def __repr__(self):
return '<%s>' % str(self.__dict__)[1:-1]
com1 = Computer('lenovo','black','8G')
com1.screen = '27寸'
com1.color = 'white'
del com1.ram
print(com1)
getattr(com1,'color')
setattr(com1,'screen','30寸')
delattr(com1,'brand')
print(com1)
2.聲明?個(gè)人的類和狗的類:
狗的屬性:名字鸟妙、顏?色焦人、年年齡
狗的?方法:叫喚
人的屬性:名字、年年齡重父、狗
人的?方法:遛狗
a.創(chuàng)建人的對(duì)象小明花椭,讓他擁有一條狗大黃,然后讓小明去遛大黃
class Dog:
"""狗 類"""
def __init__(self,name,color='red',age=5):
self.name = name
self.color = color
self.age = age
def call(self):
print('%s 在叫喚'% self.name)
class Person:
"""人 類"""
def __init__(self,name,age=15):
self.name = name
self.dog = None
self.age = age
def walk_dog(self,dog):
if not self.dog:
print('沒有狗房午!遛自己矿辽。。')
else:
print('%s 在遛 %s' % (self.name,self.dog.name))
# 創(chuàng)建人對(duì)象
p1 = Person('小明')
# 創(chuàng)建狗對(duì)象
dog1 = Dog('大黃'郭厌,15)
p1.dog = dog1
print(p1.walk_dog())
3.聲明?一個(gè)圓類袋倔,自己確定有哪些屬性和方法
class Circle:
"""圓 類"""
pi = 3.1415926
def __init__(self,r):
self.r = r
def area(self):
return pi * self.r**2
def perim(self):
return 2*pi*self.r
4.創(chuàng)建?一個(gè)學(xué)?生類:
屬性:姓名,年齡折柠,學(xué)號(hào)
方法:答到宾娜,展示學(xué)生信息
創(chuàng)建?一個(gè)班級(jí)類:
屬性:學(xué)生,班級(jí)名
方法:添加學(xué)生扇售,刪除學(xué)生前塔,點(diǎn)名, 求班上學(xué)生的平均年齡
class Student:
"""學(xué)生類"""
def __init__(self,name,age=18,study_id=0):
self.name = name
self.age = age
self.study_id = study_id
def answer(self):
return '%s 答到!' % self.name
def show(self):
print('姓名:%s承冰,年齡:%s华弓,學(xué)號(hào):%s' % (self.name,self.age,self.stud_yid))
class Class:
"""班級(jí)類"""
def __init__(self,name):
self.student = []
self.name = name
def func():
num = 1
while True:
yield 'stu'+str(num)
num += 1
self.creat_id = func()
def add_student(self):
name = input('請(qǐng)輸入學(xué)生姓名:')
age =int( input('請(qǐng)輸入學(xué)生年齡:'))
study_id = next( self.creat_id)
stu = student(name,age,study_id)
self.student.append(stu)
def show_all_student(self):
print('%s的學(xué)生' % self.name)
for stu in self.student:
stu.show()
def del_student(self):
del_name = input('請(qǐng)輸入需要?jiǎng)h除的學(xué)生姓名:')
flag = False
for stu in self.student[:]:
if stu.name == del_name:
flag = True
stu.show()
value = input('是否刪除(y/n):')
if value == 'y':
self.student.remove(stu)
if not flag:
print('沒有該學(xué)生!')
def call_name(self):
for stu in self.student:
stu.show()
stu.answer()
def avg_age():
ages = 0
for stu in self.student:
ages += stu.age
return ages/len(self.student)