python - 使用用户输入获取来自类 python3 的信息
问题描述
我对python相当陌生,我知道我做错了,但似乎找不到必须完成的方法。
我希望用户输入两次他想要的框。我想用他选择的box的值,把它们相互相加,然后打印出来,所以2x input box1应该给出80的值。
稍后我希望有可能使用更多的盒子。
class Boxes:
'boxes with assigned weight'
def __init__(self, boxnr, weight):
self.boxnr = boxnr
self.weight = weight
box1 = Boxes('box1', 40)
box2 = Boxes('box2', 70)
box3 = Boxes('box3', 110)
def tot_weight(self, weight):
if input in Boxes:
total += Boxes[weight.self]
return self.tot_weight
print ('which box?')
weight = input ()
print('what is your next box?')
weight = input ()
print (tot_weight.self.weight())
解决方案
对此代码的一些建议:
- 保持类名单数
- 只有类中的方法可以/应该使用参数
self
作为self
调用该方法的类的实例 - 如果要检查
Boxes
实例是否存在,则需要将所有实例保存Boxes
在某个列表中 - 更明确地命名变量并传递它们
- 该
input
函数接受一个prompt
字符串作为参数,这比单独的print
语句更简洁
这是一个重构:
class Box:
'''Box with assigned weight'''
def __init__(self, name, weight):
self.name = name
self.weight = weight
boxes = [
Box('box1', 40),
Box('box2', 70),
Box('box3', 110)
]
def get_box_weight_if_box_exists(box_name, boxes):
for box in boxes:
if box.name == box_name:
return box.weight
return 0
keep_adding = True
total = 0
while keep_adding:
box_name = input('Enter a box name: ')
total += get_box_weight_if_box_exists(box_name, boxes)
print('Total: {}'.format(total))
keep_adding = input('Add another? (y/n): ') == 'y'
运行时,上面的代码将继续按名称询问新盒子并将指定盒子的重量添加到总数中,直到用户输入任何内容,但'y'
被询问时'Add another? (y/n)'
。我不确定当没有给定框时您想如何处理这种情况box_name
,但是您可以将该return 0
行更改get_box_weight_if_box_exists
为几乎其他任何内容。
这是一些示例输出:
> Enter a box name: box1
Total: 40
> Add another? (y/n): y
> Enter a box name: box2
Total: 110
> Add another? (y/n): y
> Enter a box name: nice
Total: 110
> Add another? (y/n): n
如果您有任何问题,请告诉我。
推荐阅读
- sql - 不一致的数据类型:预期的 CHAR 得到了 ANYDATA
- python - 如何使用 Azure Functions Blob Trigger 和 Python 从 Blob 存储中读取 json 文件
- python - 根据条件删除字典列表中的重复项
- javascript - Vuex如何提交localStorage字符串来存储
- wordpress - 将多个关键字传递给 Search API
- laravel - stancl/tenancy:如何从全局租户数据库中获取数据?
- matlab - Matlab apriltag alddiaz / MATLAB_AprilTag3 工具箱安装
- apache-spark - pyspark - PYTHONPATH 可以用于工作节点上的 Python 解释器来查找 Python 模块吗?
- android - WhatsApp/Messenger 克隆方法
- ios - Flutter 图像选择器卡在相机上