[英]Basic Python - variables
A client asked me if I could make a system around his python application. 一位客户问我是否可以围绕他的python应用程序构建系统。 The problem is that the name of the mysql tables are variables, for example in PHP I would do this:
问题是mysql表的名称是变量,例如在PHP中,我会这样做:
<?php
$type = "facebook";
mysql_query("SELECT uid FROM users_".$type." WHERE username='foo'");
?>
Now I am trying to achieve the same thing in python, I have this block of code: 现在我试图在python中实现相同的功能,我有以下代码块:
self.exeute(
"""
SELECT uid FROM `users_FACEBOOK` WHERE `username` = 'foo'
"""
)
How can I replace "FACEBOOK" by a variable? 如何用变量替换“ FACEBOOK”? (it must be fetched using the getattr-function. I have tried
(必须使用getattr-function来获取。我已经尝试过
users_%(getattr(settings, 'TYPE'))
'users_'+str(getattr(settings, 'TYPE'))
Both give errors.. 都给错误..
FACEBOOK = <get the value>
self.execute('select uid from `users_%s` where `username`="foo"' %(FACEBOOK))
Suppose you have: 假设您有:
TYPE = 'FACEBOOK'
This will give you the string with the variable name: 这将为您提供带有变量名称的字符串:
varName = 'user_' + TYPE
and this the value in the variable: 这是变量中的值:
locals()[varName]
Take a look at the help of locals. 看一下当地人的帮助。
locals(...) locals() -> dictionary
locals(...)locals()->字典
Update and return a dictionary containing the current scope's local variables.
更新并返回包含当前作用域的局部变量的字典。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.