1.聲明?個電腦類: 屬性:品牌、顏?、內(nèi)存?小 方法:打游戲、寫代碼、看視頻
a.創(chuàng)建電腦類的對象,然后通過對象點的?方式獲取、修改、添加和刪除它的屬性
b.通過attr相關(guān)?方法去獲取、修改、添加和刪除它的屬性
class Computer():
__slots__ = ('brand', 'colour', 'memory', 'cpu', 'graphics')
def __init__(self, brand, colour, memory):
self.brand = brand
self.colour = colour
self.memory = memory
def game(self):
print('打游戲')
def code(self):
print('寫代碼')
def watch_video(self):
print('看視頻')
com = Computer('惠普', '土豪金', '8GB')
print(com.brand, com.colour, com.memory)
com.brand = '華碩'
print(com.brand)
setattr(com, 'brand', '神州')
print(com.brand)
com.cpu = 'i9 9900k '
print(com.cpu)
setattr(com, 'graphics', 'RTX 2080Ti')
print(com.graphics)
del com.colour
# print(com.colour) # AttributeError: colour
delattr(com, 'memory')
# print(com.memory) # AttributeError: memory
2.聲明?個人的類和狗的類:
狗的屬性:名字、顏色、年齡
狗的方法:叫喚
人的屬性:名字、年齡、狗
人的方法:遛狗
a.創(chuàng)建人的對象小明,讓他擁有?條狗大黃,然后讓小明去遛大黃
class Dog:
def __init__(self, name, colour, age):
self.name = name
self.colour = colour
self.age = age
def cry_out(self):
print('%s:汪汪汪' % self.name)
class Person:
def __init__(self, name, age, dog=None):
self.name = name
self.age = age
self.dog = dog
def walk_the_dog(self):
print('%s遛%s' % (self.name, self.dog))
pen1 = Person('小明','15','大黃')
pen1.walk_the_dog()
3.聲明一個圓類,自己確定有哪些屬性和方法
from math import pi
class Circle:
def __init__(self, radius, colour=None):
self.radius = radius
self.colour = colour
def area(self):
print(pi*(self.radius**2))
def perimeter(self):
print(2*pi*self.radius)
circle = Circle(6)
circle.area()
circle.perimeter()
4.創(chuàng)建一個學?生類:
屬性:姓名,年齡,學號
方法:答到,展示學生信息
創(chuàng)建一個班級類:
屬性:學生,班級名
方法:添加學生,刪除學生,點名, 求班上學生的平均年齡