- 论坛徽章:
- 0
|
回复 7# Sasoritattoo
如果你非要直接用变量名,就把它们定义到globals里吧,不过该global变量不是好的编程,有崩溃的危险。(这里改了一版贴出来)- class ObjectId(str):
- def __init__(self,obj):
- str.__init__(self,obj)
- # This is the dictionary you need to support
- key_format = {"LAT":(float,1,"lat")\
- ,"LON":(float,2,"lon")\
- ,"ObjectId":(ObjectId,3,"object")\
- }
- def test_route(requestForm,key_format):
- def check_format(requestForm,key_format):
- values = {}
- for key in key_format:
- value = requestForm[key]
- #value = request.form(key) # You can use the line in your real function
- try:
- values[key_format[key][2]] = key_format[key][0](value)
- except:
- values = (key,key_format[key][1])
- return values
- values = check_format(requestForm,key_format)
- if type(values) != type({}):
- key, err_number = values
- # deal something for the error
- print key,err_number, "heihei"
- return
- globals().update(values)
- #do_something()
- print lat, "xixixixi"
- print object, "hahaha"
- rf={"LAT":"12.0","LON":"2.0","ObjectId":"This is an example"}
- test_route(rf,key_format)
- test_route(rf,key_format)
- rf={"LAT":"12.0","LON":"ERROR2.0","ObjectId":"This is an example"}
- test_route(rf,key_format)
-
复制代码 结果- $python test_route.py
- 12.0 xixixixi
- This is an example hahaha
- LON 2 heihei
复制代码 还有一种方法是用类的属性函数,这里就不写了,但是lat前需要加个classname,用classname.lat
参考http://stackoverflow.com/questio ... -variable-in-python
不过我觉得最好的方法,也是最简单就是在后续程序中用values["lat"]来替代lat;
你说呢?
|
|