简体   繁体   English

在另一个函数中引用变量?

[英]referencing a variable in another function?

I'm an experienced TCL developer and write my own procedures to help myself along. 我是一位经验丰富的TCL开发人员,并编写了自己的程序来帮助自己。 ie a proc i call putsVar, it prints out the value of the variable in a definitave format, so I know which variable it is and what the value is "set foo 1 ; putsVar foo" Result 'foo="1"' I'd like to do the same kind of thing in python, but not finding the answer :( . In TCL I use the upvar command since I pass the name of the variable in, then I upvar and can see the value. 即proc我调用putsVar,它以definitave格式打印出变量的值,所以我知道它是哪个变量,值是什么“ set foo 1; putsVar foo”结果'foo =“ 1”'I' d想在python中做同样的事情,但找不到答案:(。。在TCL中,我使用upvar命令,因为我在其中传递了变量的名称,然后我upvar并可以看到该值。

I understand that python doesn't have an upvar type mechanism, but with its introspection capaility, I would think this is somewhat trivial, but I'm not finding the answer anywhere. 我知道python没有upvar类型机制,但是凭借其自省功能,我认为这有些琐碎,但是我在任何地方都找不到答案。

Here's how i think it should work: 这是我认为应该起作用的方式:

def printVar(var):
    valVar = "some mechanism to look up 1 level here to get value of var"
    print str(var) + "=\"" + str(valVar) + "\""

x = "Hello"
printVar("x")
x="Hello"

and extended: 并扩展:

def foo():
    y = "Hello World"
    printVar("y")

foo()
y="Hello World"

You can, but you shouldn't. 可以,但是不可以。 If your code downright needs it, then something is wrong with your design, and you probably should be using explicitly passed dictionaries or objects with proper attributes. 如果您的代码完全需要它,则您的设计有问题,您可能应该使用显式传递的字典或具有适当属性的对象。

But, to answer the question directly: you can use sys._getframe . 但是,直接回答这个问题:您可以使用sys._getframe Just be aware that this might not be portable across Python implementations (ie work only on CPython): 请注意,这可能无法跨Python实现移植(即仅在CPython上有效):

def get_object(name):
   return sys._getframe(1).f_locals[name]

x = 'foo bar'
print get_object('x')

def foo():
    y = 'baz baf'
    print get_object('y')

foo()

Perhaps I'm not 100% clear on what you want but you can expand printVar a bit so that you pass in the name of the variable (as you want it printed) as well as the variable itself. 也许我不清楚您想要什么,但可以对printVar进行一些扩展,以便您传入变量的名称(如您希望打印的那样)以及变量本身。

def printVar(var, var_name):
    print "{0} = {1}".format(var_name, var)

>>> x = 5
>>> printVar(x, "x")
x = 5
>>> y = "Hello"
>>> printVar(y, "y")
y = Hello

To my knowledge, there's no good way to get a string representation of a variable name. 据我所知,没有一种好的方法来获取变量名的字符串表示形式。 You'll have to provide it yourself. 您必须自己提供。


I'll expand it to fit your example a bit better: 我将其扩展为更好地适合您的示例:

def printVar(var, var_name):
    if type(var) is type(str()):
        print '{0} = "{1}"'.format(var_name, var)
    else:
        print '{0} = {1}'.format(var_name, var)
>>> printVar(x, "x")
x = 5
>>> printVar(y, "y")
y = "Hello"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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