English 中文(简体)
参考功能中的 Python变
原标题:Referring to Python console variable in function

我不相信斯图尔特的范围规则。 如果Im使用Salph console并界定一个变数,那么就进口一个模块,并在该模块中指定一个功能,那么该功能中是否有办法提及功能中的变数? 例如:

>> option = 2
>> import choosingModule
>> choosingModule.choosingFunction()

之后,在选择模块时:

def choosingFunction():
    if option == 0:
        doThis()
    elif option == 1:
        doThat()
    elif option == 2:
        doTheOtherOne()
    else:
        doWhateverYouFeelLike()

显然,这是一个简单的例子。 我之所以要这样做,是因为我有四种不同的功能版本,我希望能够从应该使用的独角选择。 这一功能在守则中被称作相当深,因此,我不想通过每项职能呼吁通过一个参数,特别是因为我只需要在测试阶段对其进行比较;在达到生产版本时,只能使用一个参数。

因此,在所谓的功能中,是否有任何办法提及“沙尔”变量? 或者,或许还有其他一些方式来做我所需要的事情?

问题回答

当您管理REPL时,请重新编号<>main__。 模块,使您能够进口和使用其变量:

def choosingFunction():
    option = __import__( __main__ ).option
    if option == 0:
        doThis()
    elif option == 1:
        doThat()
    elif option == 2:
        doTheOtherOne()
    else:
        doWhateverYouFeelLike()

但是,如果你绝对没有,就更能做到这一点。 术语表中要界定的变量是将其放在<条码>中。 然后:

def choosingFunction():
    global option
    if option == 0:
        doThis()
    elif option == 1:
        doThat()
    elif option == 2:
        doTheOtherOne()
    else:
        doWhateverYouFeelLike()
>>> import choosingModule
>>> choosingModule.option = 2
>>> choosingModule.choosingFunction()

However, you should only use either while testing. Please don t use these in production code.

d 我建议你利用全球发言,保持全球范围的这一变量。

关键词global允许你提及全球名称空间的一个变数,尽管在职能呼吁者上存在另一个名称相同的变量。

例如,这将印刷“实质”

def foo():
    def bar():
        return fruit
    fruit = "tangerine"
    return bar2()

fruit = "banana"
print(foo()) # will print "tangerine"

但这将印刷“香蕉”。

def foo2():
    def bar2():
        global fruit # fetch me the fruit in the global scope
        return fruit
    fruit = "tangerine"
    return bar2()

fruit = "banana"
print(foo2()) # will print "banana"

如果没有全球关键词,口译人员将遵循“LEGB规则”,以便找到你再次试图提到的变量:

  1. L ocal Scope: first, it ll search for the variable in the local scope, the scope in which your function statements are being executed. Local scopes are created everytime a function is called.
  2. E nclosing Scopes: secondly, the interpreter will look for the variable in the "enclosing function locals", that is the functions in which your function is inserted (declared). That s where the fruit variable is found on the return fruit statement inside bar().
  3. G lobal: if the variable was not found on the namespaces above, python will try to find it among the global variables. The usage of the global statement forces python to look for it only on the global scope, thus skipping 1 and 2.
  4. B uiltins: at last, python will try to find the variable among the built-in functions and constants. No magic here.

If all of the searches above fail to find the variable name, python will raise a NameError Exception:

$ NameError: name  fruit  is not defined

然后,你可以做:

def choosingFunction():
    global option
    if option == 0:
        doThis()
    elif option == 1:
        doThat()
    elif option == 2:
        doTheOtherOne()
    else:
        doWhateverYouFeelLike()

>> option = 2
>> import choosingModule
>> choosingModule.choosingFunction()

铭记依赖模块中存在一个称为你的全球变量,被认为是一种非常坏的做法,并且用吨数来形容任何严重的做法。

For more information on the global statement, check the documentation: Python 3.x and Python 2.7. And for info about the scopes and namespaces rules check here (Python 3.x) or here (Python 2.7).





相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...