简体   繁体   中英

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).

But for the module pint , it uses a dot separator as the way to get the units, like so:

from pint import *

ureg = UnitRegistry()
dist = 8 * ureg.meter
print(dist)
>>> 8 meters

Now 8 is tied to meters. But say I want to let the user define the unit. So have a variable defined by an input attached to ureg like so:

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. if inp=meters , why won't it work as ureg.meters worked? How can you attach variables to call attributes from a module?

You could use 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM