[英]How to pass one variable as another variable in a function in python
I have a SQL variable mem_dep
When I am using it directly in variable sql
then it is working absolutely fine.我有一个 SQL 变量
mem_dep
当我直接在变量sql
中使用它时,它工作得非常好。 It is printing proper SQL statement but when I am passing another variable cat
in variable sql
with the value " mem_dep
" then it is not working fine.它正在打印正确的 SQL 语句,但是当我在变量
sql
中传递另一个值为“ mem_dep
”的变量cat
时,它无法正常工作。 It is just printing value of cat
它只是
cat
的打印值
mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
cob = "20223456"
cat = "mem_dep"
Below code is working absolutely fine下面的代码工作得很好
def calc():
sql = mem_dep.format(Business_date = cob)
print(sql)
Output: Output:
calc() # calling function
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql
But below code is not working if I am passing variable cat
in a function with the same value as variable name mem_dep
但是如果我在 function 中传递与变量名
mem_dep
具有相同值的变量cat
,则下面的代码不起作用
def calc(cat):
sql = cat.format(Business_date = cob)
print(sql)
Output: Output:
calc(cat) # calling function
mem_dep #printing sql
How can I pass SQL variable as a variable in the function in this case?在这种情况下,如何将 SQL 变量作为 function 中的变量传递?
I tried below code also but not working我也尝试了下面的代码但没有工作
def calc(cat):
tmp_sql = "{}".format(cat)
sql = tmp_sql.format(Business_date = cob)
print(sql)
Output: Output:
calc(cat) # calling function
mem_dep #printing sql
Expected output:预计 output:
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456' # printing sql
Thanks!!!谢谢!!! I got it resolved by using eval(cat)
我通过使用 eval(cat) 解决了这个问题
answer would be答案是
sql = eval(cat).format(Business_date = cob)
for this output为此 output
SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '20223456'
You have to give mem_dep as an argument in the calc()您必须在 calc() 中将 mem_dep 作为参数
calc(mem_dep)
From what I understand cat
has the name of the SQL variable which contains your SQL string.据我了解
cat
具有 SQL 变量的名称,其中包含您的 SQL 字符串。 And you want to access the SQL string from cat
without knowing the value of cat
.并且您想在不知道
cat
值的情况下从cat
访问 SQL 字符串。 You can use getattr for this purpose and wrap everything in a class like below:为此,您可以使用 getattr 并将所有内容包装在 class 中,如下所示:
class SQLCalc:
def __init__(self):
self.mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
self.cob = "20223456"
self.cat = "mem_dep"
def calc(self):
sql = getattr(self, self.cat).format(Business_date = self.cob)
print(sql)
sql_calc = SQLCalc()
sql_calc.calc()
Maybe like this:也许像这样:
mem_dep = """SELECT * FROM TABLE1 WHERE DT2_BUSINESS = '{Business_date}'"""
cob = "20223456"
def calc(sql_template, buisness_date):
return sql_template.format(Business_date = buisness_date)
mem_dep_result = calc(mem_dep, cob)
print(mem_dep_result)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.