- 聲明一個電腦類: 屬性:品牌板乙、顏色护侮、內存大小 ;方法:打游戲割岛、寫代碼揍诽、看視頻
a.創(chuàng)建電腦類的對象诀蓉,然后通過對象點的方式獲取栗竖、修改、添加和刪除它的屬性
b.通過attr相關的方法去獲取渠啤、修改狐肢、添加和刪除它的屬性
class Computer:
"""說明文檔:電腦類"""
def __init__(self, brand, color, memory):
self.brand = brand
self.color = color
self.memory = memory
def play_games(self):
print('打游戲')
def write_code(self):
print('寫代碼')
def watch_video(self):
print('看視頻')
computer1 = Computer('T400', '黑色', '1T')
print('=========對象.的方式============')
# 查
print(computer1.brand)
# 改
computer1.color = '灰色'
print(computer1.color)
# 增
computer1.type = '游戲本'
print(computer1.type)
# 刪
del computer1.type
print('=========attr相關的方式============')
# 查
print(getattr(computer1, 'brand', '無'))
# 改
setattr(computer1, 'memory', '2T')
print(computer1.memory)
# 增
setattr(computer1, 'type', '游戲本')
print(computer1.type)
# 刪
delattr(computer1, 'type')
# print(computer1.type)
- 聲明一個人的類和狗的類:
狗的屬性:名字、顏色沥曹、年齡
狗的方法:叫喚
人的屬性:名字份名、年齡、狗
人的方法:遛狗
a.創(chuàng)建人的對象小明架专,讓他擁有一條狗大黃同窘,然后讓小明去遛大黃
class Dog:
"""說明文檔:狗類"""
def __init__(self, name, color, age=0):
self.name = name
self.color = color
self.age = age
def bark(self):
print('狗在叫')
class Person:
def __init__(self, dog, name, age=18):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
print(self.name + '去遛' + self.dog)
dog1 = Dog('大黃', '黃色', 2)
person1 = Person(dog1.name, '小明')
person1.walk_the_dog()
- 聲明?一個圓類,自己確定有哪些屬性和方法
import math
# 3.聲明?一個圓類部脚,自己確定有哪些屬性和方法
class Circle:
"""說明文檔:圓類"""
def __init__(self, radius):
self.radius = radius
def circle_area(self):
return self.radius ** 2 * math.pi
def circle_perimeter(self):
return self.radius * 2 * math.pi
circle1 = Circle(4)
print(circle1.circle_area())
print(circle1.circle_perimeter())
- 創(chuàng)建一個學生類:
屬性:姓名,年齡裤纹,學號
方法:答到委刘,展示學生信息
創(chuàng)建一個班級類:
屬性:學生,班級名
方法:添加學生鹰椒,刪除學生锡移,點名, 求班上學生的平均年齡
class Student:
"""說明文檔:學生類"""
def __init__(self, name, age, number):
self.name = name
self.age = age
self.number = number
def answer(self, stu_name):
print(stu_name + '回答:' + '到')
def show_stu_info(self):
print('姓名:%s 年齡:%d 學號:%s' % (self.name, self.age, self.number))
class ClassAndGrade:
"""說明文檔:班級類"""
def __init__(self, class_name):
self.stu_name = []
self.class_name = class_name
def add_stu(self, student):
self.stu_name.append(student)
def del_stu(self, student_name):
if not self.stu_name:
print('沒有可刪除的學生')
for item in self.stu_name:
if item['name'] == student_name:
del item
else:
print('沒有找到該學生')
def call_the_roll(self):
if not self.stu_name:
print('沒有學生')
for item in self.stu_name:
print(item['name'])
def avg_age(self):
sum1 = 0
for item in self.stu_name:
sum1 += item['age']
print(sum1/len(self.stu_name))