#!/usr/bin/env Python
# -*- coding:utf-8 -*-
# transfer.py
# 翻译小程序 用面向对象的思想进行重构
class Transfer(object):
"""单位转换的输入输出"""
def __init__(self):
self.welcome()
self.converter = self.convert_choose()
self.converter()
def welcome(self):
menu = {
"1":"温度转换",
'2':'长度转换',
'3':'货币转换',
'q':'退出'
}
for k,v in menu:
print(f'{k}:{v}')
def convert_choose(self):
converter = None # 定义一个转换器
while True:
choose = input('请输入转换的类型(Q退出)').upper()
if choose == '1':
converter = Temperature
elif choose == "2":
converter = Length
elif choose == '3':
converter = Currency
elif choose == "Q":
print("退出")
exit()
else:
print('输入错误,请重新输入')
continue
return converter
class Temperature(object):
"""温度转换"""
def __init__(self):
self.user_input()
def user_input(self):
"输入入口"
temp = input("请输入要转换的值(1C 1F,Q退出)").upper()
while True:
if temp.endswith("C"):
try:
temp = float(temp.strip("C"))
except:
print('请按照提示输入')
res = f'{temp}转换为华氏度为{self.c_to_f(temp)}'
elif temp.endswith('F'):
try:
temp = float(temp.strip("F"))
except:
print('请按照提示输入')
res = f'{temp}转换为摄氏度为{self.f_to_c(temp)}'
elif temp == "Q":
exit()
else:
res = None
print('输入不正确,请重新输入')
continue
print(res)
def c_to_f(self, num):
"摄氏度转华氏度"
num1 = ( 9 / 5 ) * num + 32
round(num1, 0)
return num1
def f_to_c(self, num):
"华氏度转摄氏度"
num1 = ( 5 / 9 ) * num - 32
round(num1, 0)
return num1
class Length:
"""长度转换"""
def __init__(self):
self.user_input()
def user_input(self):
"输入入口"
temp = input("请输入要转换的值(1m 1foot,Q退出)").upper()
while True:
if temp.endswith("M"):
try:
temp = float(temp.strip("M"))
except:
print('请按照提示输入')
res = f'{temp}转换为英尺为{self.m_to_ft(temp)}'
elif temp.endswith('FOOT'):
try:
temp = float(temp.strip("F"))
except:
print('请按照提示输入')
res = f'{temp}转换为米为{self.m_to_ft(temp)}'
elif temp == "Q":
exit()
else:
res = None
print('输入不正确,请重新输入')
continue
print(res)
def m_to_ft(self, num):
"米转化为英尺"
num1 = num * 3.2808399
round(num1, 0)
return num1
def ft_to_m(self, num):
"英尺转化成米"
num1 = num * 0.3048
round(num1, 0)
return num1
class Currency:
"""货币转换"""
def __init__(self):
self.user_input()
def user_input(self):
"输入入口"
temp = input("请输入要转换的值(1rmb 1d,Q退出)").upper()
while True:
if temp.endswith("RMB"):
try:
temp = float(temp.strip("RMB"))
except:
print('请按照提示输入')
res = f'{temp}转换为美金为{self.r_to_d(temp)}'
elif temp.endswith('D'):
try:
temp = float(temp.strip("D"))
except:
print('请按照提示输入')
res = f'{temp}转换为人民币为{self.r_to_d(temp)}'
elif temp == "Q":
exit()
else:
res = None
print('输入不正确')
continue
print(res)
def r_to_d(self, num):
"人民币转化为美金"
num1 = num * 0.1404
round(num1, 0)
return num1
def d_to_r(self, num):
"美金转化为人民币"
num1 = num * 7.1218
round(num1, 0)
return num1
def main():
x = Transfer()
x.welcome()
if __name__ == "__main__":
main()
Python如何对这个程序进行实例化并正确输出?
Python如何对这个程序进行实例化并正确输出?
- 写回答
- 好问题 0 提建议
- 追加酬金
- 关注问题
- 邀请回答
-
2条回答 默认 最新
- huache 2019-10-26 00:56关注
代码有一些问题,我做了一些修改。在 python 3.7 下简单测试了一下,可以正常运行。
主要问题是
while True
没有使用break
退出,程序无法往下运行。另外,input
语句需要放在while True
内部,这样才能实现输错后重新输入。至于实例化的问题。我的理解,代码演示的是 简单工厂模式,
Transfer
类就是一个简单工厂类,根据用户的输入,返回指定的Converter
类,并赋给self.converter
。具体的实例化语句就是
self.converter()
这一句,从功能上来说,这一句和x = Transfer()
是类似的,区别只在于self.converter
由用户的输入来动态地决定是哪一个类。这是基于 Python 的动态特性,所以可以用一行语句统一进行实例化。如果是 Java 实现,就必须定义一个接口,所有
Converter
都实现这个接口,然后,在convert_choose
方法里的每一个条件分支里面实例化相应的类。网上的例子有很多,比如这个简单工厂 Java 版,链接的例子中的加减乘除,就对应这里的各种Converter
。最后,个人觉得在
__init__()
方法里面直接触发操作,并不是一个好的代码风格,仅供参考。#!/usr/bin/env Python # -*- coding:utf-8 -*- # transfer.py # 翻译小程序 用面向对象的思想进行重构 class Transfer(object): """单位转换的输入输出""" def __init__(self): self.welcome() self.converter = self.convert_choose() self.converter() # 实例化 def welcome(self): menu = { "1":"温度转换", '2':'长度转换', '3':'货币转换', 'q':'退出' } for k,v in menu.items(): print(f'{k}:{v}') def convert_choose(self): converter = None # 定义一个转换器 while True: choose = input('请输入转换的类型(Q退出)').upper() if choose == '1': converter = Temperature elif choose == "2": converter = Length elif choose == '3': converter = Currency elif choose == "Q": print("退出") exit() else: print('输入错误,请重新输入') continue break return converter class Temperature(object): """温度转换""" def __init__(self): self.user_input() def user_input(self): "输入入口" while True: temp = input("请输入要转换的值(1C 1F,Q退出)").upper() if temp.endswith("C"): try: temp = float(temp.strip("C")) except: print('请按照提示输入') res = f'{temp}转换为华氏度为{self.c_to_f(temp)}' elif temp.endswith('F'): try: temp = float(temp.strip("F")) except: print('请按照提示输入') res = f'{temp}转换为摄氏度为{self.f_to_c(temp)}' elif temp == "Q": exit() else: res = None print('输入不正确,请重新输入') continue break print(res) def c_to_f(self, num): "摄氏度转华氏度" num1 = ( 9 / 5 ) * num + 32 round(num1, 0) return num1 def f_to_c(self, num): "华氏度转摄氏度" num1 = ( 5 / 9 ) * num - 32 round(num1, 0) return num1 class Length: """长度转换""" def __init__(self): self.user_input() def user_input(self): "输入入口" while True: temp = input("请输入要转换的值(1m 1foot,Q退出)").upper() if temp.endswith("M"): try: temp = float(temp.strip("M")) except: print('请按照提示输入') res = f'{temp}转换为英尺为{self.m_to_ft(temp)}' elif temp.endswith('FOOT'): try: temp = float(temp.strip("F")) except: print('请按照提示输入') res = f'{temp}转换为米为{self.m_to_ft(temp)}' elif temp == "Q": exit() else: res = None print('输入不正确,请重新输入') continue break print(res) def m_to_ft(self, num): "米转化为英尺" num1 = num * 3.2808399 round(num1, 0) return num1 def ft_to_m(self, num): "英尺转化成米" num1 = num * 0.3048 round(num1, 0) return num1 class Currency: """货币转换""" def __init__(self): self.user_input() def user_input(self): "输入入口" while True: temp = input("请输入要转换的值(1rmb 1d,Q退出)").upper() if temp.endswith("RMB"): try: temp = float(temp.strip("RMB")) except: print('请按照提示输入') res = f'{temp}转换为美金为{self.r_to_d(temp)}' elif temp.endswith('D'): try: temp = float(temp.strip("D")) except: print('请按照提示输入') res = f'{temp}转换为人民币为{self.r_to_d(temp)}' elif temp == "Q": exit() else: res = None print('输入不正确') continue break print(res) def r_to_d(self, num): "人民币转化为美金" num1 = num * 0.1404 round(num1, 0) return num1 def d_to_r(self, num): "美金转化为人民币" num1 = num * 7.1218 round(num1, 0) return num1 def main(): x = Transfer() #x.welcome() if __name__ == "__main__": main()
本回答被题主选为最佳回答 , 对您是否有帮助呢?解决 无用评论 打赏 举报
悬赏问题
- ¥15 matlab求解平差
- ¥15 电脑桌面设定一个区域禁止鼠标操作
- ¥15 求NPF226060磁芯的详细资料
- ¥15 使用R语言marginaleffects包进行边际效应图绘制
- ¥20 usb设备兼容性问题
- ¥15 错误(10048): “调用exui内部功能”库命令的参数“参数4”不能接受空数据。怎么解决啊
- ¥15 安装svn网络有问题怎么办
- ¥15 vue2登录调用后端接口如何实现
- ¥65 永磁型步进电机PID算法
- ¥15 sqlite 附加(attach database)加密数据库时,返回26是什么原因呢?