[英]Python Dot Separator with Variable Input
I'm currently attempting to write a program that takes in a user input of units and magnitude and converts them to a user defines the unit. 我目前正在尝试编写一个程序,该程序接受用户输入的单位和大小并将其转换为用户定义的单位。 So basically just a unit converter (still doing beginner projects with Python).
因此,基本上只是一个单位转换器(仍然使用Python进行初学者项目)。
But for the module pint
, it uses a dot separator as the way to get the units, like so: 但是对于
pint
模块,它使用点分隔符作为获取单位的方式,如下所示:
from pint import *
ureg = UnitRegistry()
dist = 8 * ureg.meter
print(dist)
>>> 8 meters
Now 8 is tied to meters. 现在8与米挂钩。 But say I want to let the user define the unit.
但是说我想让用户定义单位。 So have a variable defined by an input attached to
ureg
like so: 因此,通过连接到
ureg
的输入定义一个变量, ureg
所示:
from pint import *
ureg = UnitRegistry()
inp = input()
>>>inp = meter
unit = ureg.inp # this is a variable defined by user
step = 8 * unit
print(step)
>>>AttributeError: 'UnitRegistry' object has no attribute '_inp_'
The problem is python thinks I'm trying to access an attribute called inp
from ureg
, which doesn't exist. 问题是蟒蛇认为我试图访问称为属性
inp
从ureg
,它不存在。 if inp=meters
, why won't it work as ureg.meters
worked? 如果
inp=meters
,为什么它不能像ureg.meters
起作用? How can you attach variables to call attributes from a module? 如何附加变量以从模块调用属性?
You could use getattr(object, name)
: 您可以使用
getattr(object, name)
:
ureg = UnitRegistry()
user_value = input()
unit = getattr(ureg, user_value) # this is a variable defined by user
step = 8 * unit
print(step)
Or: 要么:
ureg = UnitRegistry()
user_value = input()
unit = vars(ureg)[user_value] # this is a variable defined by user
step = 8 * unit
print(step)
Or: 要么:
eval('ureg.%s()'%user_value)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.