先有类在有对象
用类去创建一个对象 (创建 = 实例)
类是对一系列具有相同特征(属性)和行为(方法)的事物的统称
class 类名(要继承的类名): ...
实例:对象名 = 类名()
print(对象名) 输出一段地址,表示创建成功
魔法方法
_ xx _
_ init _:添加实例属性
class Washer(): def __init__(self): #添加实例属性 self.width = 500 self.height = 800 def print_info(self): print(f'洗衣机的宽度{self.width},洗衣机的高度{self.height}') washer = Washer() washer.print_info() #洗衣机的宽度500,洗衣机的高度800
带参数的_ init_()
更麻烦了
class Washer(): def __init__(self,width,height): #添加实例属性 self.width = width self.height = height def print_info(self): print(f'洗衣机的宽度{self.width},洗衣机的高度{self.height}') washer1 = Washer(100,200) washer2 = Washer(400,600) washer1.print_info() #洗衣机的宽度100,洗衣机的高度200 washer2.print_info() #洗衣机的宽度400,洗衣机的高度600
_ str _()
若类定义了这个方法,那么就会打印从在这个方法中return的数据、
class Washer(): def __init__(self,width,height): #添加实例属性 self.width = width self.height = height def __str__(self): return '洗衣机说明书' washer1 = Washer(10,20) print(washer1) #洗衣机说明书
__ del __()
当删除对象时,python解释器会默认调用此方法
class Washer(): def __init__(self,width,height): #添加实例属性 self.width = width self.height = height def __del__(self): print('删了') washer1 = Washer(10,20) #删了
烤地瓜
# 1,定义一个地瓜类:初始化属性、被烤和添加调料的方法、显示对象信息的str class SweetPotato(): def __init__(self): # 被烤的时间 self.cook_time = 0 # 烤的状态 self.cook_state = '生' # 调料 self.condiments = [] def cook(self, time): """烤地瓜的方法""" self.cook_time += time if 0 <= self.cook_time < 3: self.cook_state = '生的' elif 3 <= self.cook_time<5: self.cook_state = '半生不熟' elif 5 <= self.cook_time < 8: self.cook_state = '熟了' else: self.cook_state = '糊了sb' # 输出对象状态 def __str__(self): return f'这个地瓜烤了{self.cook_time}min,{self.cook_state},加了{self.condiments}' # 加调料 def add_condiments(self,condiments): self.condiments.append(condiments) # 2.创建对象并且调用对应的实例方法 sp = SweetPotato() print(sp) #这个地瓜烤了0min,生,加了[] sp.cook(4) print(sp) #这个地瓜烤了0min,生,加了[] sp.add_condiments('黑椒') print(sp) #这个地瓜烤了4min,半生不熟,加了['黑椒']
搬家具
将小于房子剩余面积的家具摆放到房子里
# 房子类 class Home(): def __init__(self, address,area): self.address = address self.area = area self.free_area = area self.furniture = [] def __str__(self): return f'地址是{self.address},占地面积{self.area},' \ f'剩余面积{self.free_area},家具有{self.furniture}' def add_furniture(self, item): if self.free_area >= item.area: self.furniture.append(item.name) self.free_area -= item.area else: print('换个大点的房子') # 家具类 class Furniture(): def __init__(self, name, area): self.name = name self.area = area bed = Furniture('bed', 6) table = Furniture('table', 4) box = Furniture('box', 1) Home = Home('人民公园', 5) Home.add_furniture(box) Home.add_furniture(table) Home.add_furniture(bed) print(Home) # 换个大点的房子 # 地址是人民公园,占地面积5,剩余面积0,家具有['box', 'table']