1.聲明一個(gè)電腦類: 屬性:品牌留荔、顏色吟孙、內(nèi)存大小 方法:打游戲、寫代碼、看視頻
class Computer:
def __init__(self, brand, color, memory, ):
self.brand = brand
self.color = color
self.memory = memory
def game(self):
return '用%s的電腦打游戲' % self.brand
def code(self):
return '用%s的電腦寫代碼' % self.brand
def video(self):
return '用%s的電腦看視頻' % self.brand
a.創(chuàng)建電腦類的對(duì)象杰妓,然后通過對(duì)象點(diǎn)的方式獲取藻治、修改、添加和刪除它的屬性
com1 = Computer('聯(lián)想', '紅色', '8GB')
print(com1.color)
com1.color = '黑色'
print(com1.color)
com1.cpu = 'i5'
print(com1.cpu)
del com1.brand
b.通過attr相關(guān)方法去獲取巷挥、修改桩卵、添加和刪除它的屬性
com2 = Computer('蘋果', '灰色', '4GB')
print(getattr(com2, 'color'))
setattr(com2, 'color', '白色')
print(getattr(com2, 'color'))
setattr(com2, 'cpu', 'os')
print(getattr(com2, 'cpu'))
delattr(com2, 'memory')
2.聲明一個(gè)人的類和狗的類:
狗的屬性:名字、顏色句各、年齡
狗的方法:叫喚
人的屬性:名字吸占、年齡晴叨、狗
人的方法:遛狗
a.創(chuàng)建人的對(duì)象小明凿宾,讓他擁有一條狗大黃,然后讓小明去遛大黃
class Dog:
def __init__(self, name1, color, age1):
self.name = name1
self.color = color
self.age = age1
@staticmethod
def bark():
print('叫喚')
class Person:
def __init__(self, name2, age2, dog):
self.name = name2
self.age = age2
self.dog = dog
def walkTheDog(self):
print('%s遛%s' % (self.name, self.dog))
dog1 = Dog('大黃', '黃色', 3)
person1 = Person('小明', 23, dog1.name)
person1.walkTheDog()
3.聲明一個(gè)圓類兼蕊,自己確定有哪些屬性和方法
import math
n = math.pi
class Circle:
def __init__(self, radius):
self.radius = radius
def perimeter(self):
return 2 * n * self.radius
def area(self):
return n * (self.radius ** 2)
4.創(chuàng)建一個(gè)學(xué)生類:
屬性:姓名初厚,年齡,學(xué)號(hào)
方法:答到孙技,展示學(xué)?生信息
創(chuàng)建一個(gè)班級(jí)類:
屬性:學(xué)生产禾,班級(jí)名
方法:添加學(xué)生,刪除學(xué)生牵啦,點(diǎn)名, 求班上學(xué)生的平均年齡
class Student:
def __init__(self, name, age, num):
self.name = name
self.age = age
self.num = num
def class_name(self):
print('到,我叫%s,年齡%d歲,學(xué)號(hào)%d'%(self.name,self.age,self.num))
def dict1(self):
dict1 = {'姓名':self.name,'年齡':self.age,'學(xué)號(hào)':self.num}
return dict1
stu1 = Student('小明',17,23)
stu1.class_name()
stu2 = Student('小紅',18,24)
stu3 = Student('小聰',20,45)
class Class:
def __init__(self,list1=[],class_name='一班'):
self.student = list1
self.class_name = class_name
def add_stu(self,student):
"""添加學(xué)生"""
self.student.append(student)
print(self.student)
def delete(self,student):
self.student.remove(student)
print(self.student)
def call_name(self):
for item in self.student:
print(item['姓名'])
def v_age(self):
count = 0
sum = 0
for item in self.student:
sum += item['年齡']
count+=1
print(sum/count)
c1 = Class([stu1.dict1()])
c1.add_stu(stu2.dict1())
c1.add_stu(stu3.dict1())
c1.v_age()