1.聲明?個(gè)電腦類: 屬性:品牌、顏?锐秦、內(nèi)存?小 方法:打游戲咪奖、寫代碼、看視頻
a.創(chuàng)建電腦類的對(duì)象酱床,然后通過對(duì)象點(diǎn)的?方式獲取羊赵、修改、添加和刪除它的屬性
b.通過attr相關(guān)?方法去獲取扇谣、修改昧捷、添加和刪除它的屬性
class Computer(object):
def __init__(self, color, memory, brand="華為"):
self.color = color
self.memory = memory
self.brand = brand
def play_games(self):
print("打游戲嘍")
def code(self):
print("寫代碼嘍")
def see_video(self):
print("看視頻嘍")
p1 = Computer('blank','512G')
getattr(p1, 'color')
print(p1.color)
setattr(p1, 'color', 'red')
print(p1.color)
p1.size = '1024*2048'
print(p1.size)
delattr(p1, 'color')
print(p1.color)
2.聲明?個(gè)人的類和狗的類:
狗的屬性:名字、顏?色罐寨、年年齡
狗的?方法:叫喚
人的屬性:名字靡挥、年年齡、狗
人的?方法:遛狗
a.創(chuàng)建?人的對(duì)象?小明鸯绿,讓他擁有?一條狗?大?黃跋破,然后讓?小明去遛?大?黃
class Person(object):
def __init__(self, name, age, dog='小黑'):
self.name = name
self.age = age
self.dog = dog
def walk_dog(self):
print("和%s遛圈圈去了" % self.dog)
class Dog(object):
def __init__(self, name, color, age):
self.name = name
self.color = color
self.age = age
p1 = Person('小明', 20)
p2 = Dog('大黃', 'yellow', 2)
p1.dog = p2.name
print(p1.walk_dog())
3.聲明?一個(gè)圓類簸淀,自己確定有哪些屬性和方法
import math
class Round(object):
def __init__(self, radius):
self.radius = radius
def area(self):
area1 = math.pi * (self.radius ** 2)
return area1
def perimeter(self):
perimeter = math.pi * 2 * self.radius
return perimeter
p1 = Round(2)
print(p1.area())
print(p1.perimeter())
4.創(chuàng)建?一個(gè)學(xué)?生類:
屬性:姓名,年齡毒返,學(xué)號(hào)
方法:答到租幕,展示學(xué)?生信息
class Student(object):
def __init__(self, name, age, idcard):
self.name = name
self.age = age
self.idcard = idcard
def answer(self):
print("學(xué)生的姓名是%s,年齡%s歲,學(xué)號(hào)是%s"%(self.name, self.age, self.idcard))
p1 = Student("劉德華", 18, 123456)
print(p1.answer())
創(chuàng)建?一個(gè)班級(jí)類:
屬性:學(xué)?生,班級(jí)名
方法:添加學(xué)?生拧簸,刪除學(xué)生劲绪,點(diǎn)名, 求班上學(xué)生的平均年齡
class Class(object):
def __init__(self, classid, list1=[], list2=[]):
self.list1 = list1
self.list2 = list2
self.classid = classid
def add_student(self,name,age):
self.list1.append(name)
self.list2.append(age)
return self.list1, self.list2
def del_student(self,name,age):
self.list1.remove(name)
self.list2.remove(age)
return self.list1, self.list2
def call_rool(self, name):
if name in self.list1:
print("學(xué)生%s已在教室" % name)
else:
print("學(xué)生%s沒在教室" % name)
def ave_age(self):
sum = 0
n = 0
for i in self.list2:
sum += i
n += 1
return sum / n
p1 = Class(1, ['王一'], [18])
print(p1.add_student("王二", 18))
print(p1.add_student("王三", 18))
print(p1.add_student("王四", 17))
print(p1.add_student("王五", 20))
print(p1.del_student("王一", 18))
p1.call_rool("王二")
print(p1.ave_age())