我试图查看是否可以从变量执行命令
我想要的例子:
variable = print ("something")
print ("Done")
然后能够通过在此之后写入变量名来打印它。 例如:
variable
但是当我尝试输出时是:
something
Done
我知道你可以通过在变量中写下你想要打印的东西来做到这一点,但我想将它用于其他命令。
答案 0 :(得分:2)
为此你定义了函数,或者在这个简短的例子中你可以将它包装成lambda函数:
print_that = lambda: print("something")
print_that()
print("done")
您使用()
调用它。 print_that
就是您所谓的variabel
。使用函数,您可以执行更多命令:
def print_that():
print("something")
print("something else")
答案 1 :(得分:0)
您可以使用functools.partial使用一些固定参数调用任何已定义的函数。
from functools import partial
print_something = partial(print, "something")
# Use () to call as a normal function
print_something() # prints "something"
# You can pass more arguments later
print_something("another thing") # prints "something another thing"