import math
1.聲明?個電腦類: 屬性:品牌混巧、顏?、內(nèi)存?小 方法:打游戲勤揩、寫代碼咧党、看視頻
class Computer:
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play(self):
print('play game')
def write(self):
print('write code!')
def watch(self):
print('watch avi!')
c1 = Computer('聯(lián)想', 'black', '16G')
# a.方法
print(c1.color)
c1.memory = '32G'
c1.cpu = 'i9-9900k'
del c1.color
print(c1.brand, c1.memory, c1.cpu)
# b.attr方式
print(getattr(c1, 'cpu', 'i7-8700'))
setattr(c1, 'memory', '64G')
setattr(c1, 'VGA', 'TITAN RTX')
delattr(c1, 'brand')
print(c1.cpu, c1.VGA, c1.memory)
2.聲明?個人的類和狗的類:
狗的屬性:名字、顏色陨亡、年齡
狗的方法:叫喚
人的屬性:名字傍衡、年齡、狗
人的方法:遛狗
a.創(chuàng)建人的對象小明数苫,讓他擁有一條狗大黃聪舒,然后讓小明去遛大黃
class Dog:
def __init__(self, dogname, color='black', dogage=1):
self.dogname = dogname
self.color = color
self.dogage = dogage
def shout(self):
print('汪汪汪!')
class Person:
def __init__(self, name, dog:Dog=None, age=22):
self.name = name
self.age = age
self.dog = dog
def stroll(self):
if self.dog:
print('%s正在遛%s' % (self.name, self.dog))
else:
print('沒有狗虐急!遛自己')
p2 = Dog('大黃')
p1 = Person('小明', p2.dog)
p1.stroll()
3.聲明一個圓類
import math
class circle:
def __init__(self, radius):
self.radius = radius
def area(self):
return math.pi * self.radius ** 2
def peri(self):
return math.pi * self.radius * 2
4.創(chuàng)建一個學(xué)?生類:
屬性:姓名箱残,年齡,學(xué)號
方法:答到止吁,展示學(xué)生信息
class student:
def __init__(self, name, age=12, id='1001'):
self.name = name
self.age = age
self.id = id
def answ(self, name):
print('%s到被辑!' % name)
def show(self, name, age, id):
print('姓名:%s,年齡:%d,學(xué)號:%s' % (name, age, id))
def __repr__(self):
return '姓名:%s敬惦,年齡:%d,學(xué)號:%s' % (self.name, self.age, self.id)
s1 = student('小明')
s1.answ(s1.name)
s1.show(s1.name, s1.age, s1.id)
5.創(chuàng)建一個班級類:
屬性:學(xué)生盼理,班級名
方法:添加學(xué)生,刪除學(xué)生俄删,點(diǎn)名, 求班上學(xué)生的平均年齡
class CLASS:
students = []
def __init__(self, clasnum):
self.clasnum = clasnum
def addstu(self, student):
self.students.append(student.__dict__)
def del_stu(self, student):
self.students.__delattr__(student)
def call(self, student):
print(student)
def aveg(self, students):
sum = 0
for i in students:
sum += i['age']
return sum / len(students)
s2 = student('小u', 13)
s3 = student('小hong', 14)
s4 = student('gang', 32)
C1 = CLASS(1)
C1.addstu(s2)
C1.addstu(s3)
C1.addstu(s4)
C1.call(s2.name)
print(C1.aveg(C1.students))