python中的面向对象

# 面向对象是非常重要的!
# 抽象,是个思想,结构
# 小明 小红 小雨 都是人
# 海尔洗衣机 海东洗衣机 海西洗衣机 都是洗衣机
# 猫 狗 熊猫 都是动物
# 蓝图
#
# class WashingMachine: # 类名一般是大驼峰
# pass
# # 特征是属性
# age = 20
# # 行为是方法
# def
# 先有类,后有对象
# 做一张蓝图,生成洗衣机
class WashingMachine: # 洗衣机
 width = 595
 height = 850
 # 功能:会洗衣服
 def canDoLaundry(self):
 print('会洗衣服')
# 生成对象
haier = WashingMachine()
# 获取属性
print(haier.height)
print(haier.width)
haier.canDoLaundry()
# 添加属性
haier.color = 'red'
print(haier.color)
# 修改属性
haier.height = 800
print(haier.height)

运行后得:

 

 

# 如果说 class 是 英雄
# 那么可以说 魔法方法 是英雄的 被动技能 自动生效 基于一定的条件来触发
# 重构->重命名 修改某一范围的所有特定变量名称,一般选择当前文件
# 魔法方法 __xxx__()
print('魔法方法')
# # add str init del
class WashingMachine: # 洗衣机类
 def __init__(self, width, height): # 初始化属性
 self.width = width
 self.height = height
 def __add__(self, other): # 当执行加法时自动触发
 self.width += other
 self.height += other
 return self # 感觉是迭代,返回 对象 ,就可以加多个数
 def __str__(self): # 当使用print时触发
 """海尔说明书"""
 return f'高度为:{self.height}\n宽度为:{self.width}'
 def __del__(self): # 当删除时触发
 print('del魔法方法被触发了')
haier = WashingMachine(850, 595) # 触发__init__
haier + 2 + 3 # 触发__add__
print(haier) # 触发__str__
del haier # 触发__del__

 

 

 

# 私有属性 在属性名称的前面加一个下划线
# # 烤地瓜 红薯
class SweetPotato:
 def __init__(self):
 """初始化"""
 self._times = 0
 self._status = '生的'
 self._seasoning = [] # 加的调料
 def roasted_Sweet(self, times): # 烤地瓜
 """烤地瓜"""
 # 0-2分钟是生的 2-5是半生 5-8刚刚好 8分钟以上烤焦了
 self._times += times # 可能烤了之后再次烤
 if 0<= self._times <= 2:
 self._status = '生的'
 elif 3 <= self._times <= 5:
 self._status = '半生'
 elif 6 <= self._times <= 8:
 self._status = '刚刚好'
 elif self._times >= 9:
 self._status = '烤焦了'
 def add_seasoning(self, *season): # 增加调料 这有个不定长传参
 """增加调料"""
 for i in season:
 self._seasoning.append(i)
 def __str__(self): # 查看红薯的状态
 return f'红薯烤的时间:{self._times}分钟\n' \
 f'红薯的状态是:{self._status}\n' \
 f'红薯目前的调料是:{" ".join(self._seasoning)}'
sweet1 = SweetPotato()
sweet1.add_seasoning('番茄酱', '孜然')
sweet1.roasted_Sweet(3)
sweet1.roasted_Sweet(3)
sweet1.add_seasoning('番茄酱', '孜然')
print(sweet1)

 

 

# 今日练习
'''
1)定义名为MyTime(我的时间)的类
2)其中应有三个实例变量 时hour 分minute 秒second
3)对时分秒进行初始化,写入__init__()中
4)定义方法get和set方法,
 get方法获取时间,set可以设置时间
5)调用set设置时间
 调用get输出时间
'''
print()
print('今日练习')
class MyTime:
 def __init__(self, hour, minute, second):
 """初始化"""
 self.hour = hour
 self.minute = minute
 self.second = second
 def set(self, h, m, s):
 """时间变化"""
 self.hour += h
 self.minute += m
 self.second += s
 def get(self):
 """输出时间"""
 print(f'时间是{self.hour}小时{self.minute}分钟{self.second}秒')
data = MyTime(23, 9, 1)
data.set(0, 1, 59)
data.get()

 

作者:落落呀原文地址:https://www.cnblogs.com/qc2012/p/16934134.html

%s 个评论

要回复文章请先登录注册