向?qū)ο笞鳂I(yè)1:
1.聲明 個電腦類: 屬性:品牌恨课、顏 惰说、內(nèi)存 法:打游戲磨德、寫代碼、看視頻
a.創(chuàng)建電腦類的對象吆视,然后通過對象點的 式獲取典挑、修改、添加和刪除它的屬性 b.通過attr相關(guān) 法去獲取啦吧、修改您觉、添加和刪除它的屬性
class Computer:
def __init__(self,brand='聯(lián)想',color='紅色',memory='1T'):
self.brand=brand
self.color=color
self.memory=memory
@staticmethod
def fun1(game):
print('我在打%s'%game)
@staticmethod
def fun2(code):
print('我在寫%s'%code)
@staticmethod
def fun3(movie):
print('我在看%s'%movie)
c1=Computer()
c1.fun1('英雄聯(lián)盟')
c1.fun2('代碼')
c1.fun3('龍門客棧')
結(jié)果:
我在打英雄聯(lián)盟
我在寫代碼
我在看龍門客棧
c1=Computer()
#1.獲取
print(c1.brand)
print(c1.__getattribute__('brand'))
#2.修改
c1.brand='華碩'
c1.__setattr__('brand','華碩')
print(c1.brand)
#3.增加
c1.price='10萬'
c1.__setattr__('price','10萬')
print(c1.price)
#4.
del c1.price
c1.__delattr__('price')
print(c1.price)
結(jié)果:
聯(lián)想
聯(lián)想
華碩
10萬
2.聲明 個 的類和狗的類:
狗的屬性:名字、顏 丰滑、 齡 狗的 法:叫喚 的屬性:名字顾犹、 齡、狗 的 法:遛狗 a.創(chuàng)建 的對象 明褒墨,讓他擁有 條狗 炫刷,然后讓 明去遛
class Dog:
def __init__(self):
self.name='大黃'
self.color='yellow'
self.age=3
def fun1(self):
print('%s叫喚'%self.name)
d1=Dog()
class Person:
def __init__(self):
self.name='小明'
self.age=23
self.dog=d1
def fun2(self):
print('%s牽著%s在街上遛狗'%(self.name,self.dog.name))
p1=Person()
p1.fun2()
結(jié)果:
小明牽著大黃在街上遛狗
3.聲明 個矩形類:
屬性: 、寬 法:計算周 和 積 a.創(chuàng)建 同的矩形郁妈,并且打印其周 和 積
class Rectangle:
def __init__(self, length1, width1):
self.length = length1
self.width = width1
def area(self):
return self.length * self.width
def perimeter(self):
return (self.length + self.width) * 2
r1=Rectangle(10,20)
a1=r1.perimeter()
p1=r1.area()
print('周長:%s'% a1)
print('面積:%s'% p1)
結(jié)果:
周長:60
面積:200
4.創(chuàng)建 個學(xué) 類:
屬性:姓名浑玛, 齡,學(xué)號 法:答到噩咪,展示學(xué) 信息 創(chuàng)建 個班級類: 屬性:學(xué) 顾彰,班級名 法:添加學(xué) ,刪除學(xué) ,點名
lass Student:
def __init__(self,name,age,stuid):
self.name=name
self.age=age
self.stuid=stuid
def answer(self):
print('%s到了'%self.name)
def print_info(self):
print('我是%s,今年%s,學(xué)號%s,'%(self.name,self.age,self.stuid))
class Class:
def __init__(self,classname):
self.student_list=[]
self.classname=classname
def add_student(self,student):
self.student_list.append(student)
def del_student(self,student):
if self.student_list:
self.student_list.remove(student)
def dian_ming(self):
if self.student_list:
for student in self.student_list:
print(student.name)
student.answer()
s1 = Student('劉備','25','001')
s2 = Student("關(guān)羽",'22','002')
s3=Student('張飛','18','003')
c1 = Class('1班')
c1.student_list=[s1,s2]
c1.add_student(s3)
c1.dian_ming()
c1.del_student(s3)
c1.dian_ming()
結(jié)果:
劉備
劉備到了
關(guān)羽
關(guān)羽到了
張飛
張飛到了
劉備
劉備到了
關(guān)羽
關(guān)羽到了