如何在函数中创建或使用全局变量?
如果我在一个函数中创建一个全局变量,我如何在另一个函数中使用该全局变量?我是否需要将全局变量存储在需要访问的函数的局部变量中?
Python范围规则究竟是什么?
如果我有一些代码:
code1
class Foo:
code2
def spam.....
code3
for code4..:
code5
x()
Run Code Online (Sandbox Code Playgroud)
在哪里x找到?一些可能的选择包括以下列表:
在执行期间,当函数spam在其他地方传递时,也存在上下文.也许lambda函数的传递方式有点不同?
某处必须有简单的参考或算法.对于中级Python程序员来说,这是一个令人困惑的世界.
以下代码在Python 2.5和3.0中按预期工作:
a, b, c = (1, 2, 3)
print(a, b, c)
def test():
print(a)
print(b)
print(c) # (A)
#c+=1 # (B)
test()
Run Code Online (Sandbox Code Playgroud)
但是,当我取消注释行(B)时,我得到了UnboundLocalError: 'c' not assigned一行(A).的值a和b被正确地打印.这让我感到困惑,原因有两个:
为什么在行(A)处抛出运行时错误,因为后面的行(B)语句?
为什么变量a和b打印符合预期,同时c引发错误?
我能想到的唯一解释是,赋值创建了一个局部变量,即使在创建局部变量之前,它也优先于"全局"变量.当然,变量在存在之前"窃取"范围是没有意义的.cc+=1c
有人可以解释一下这种行为吗?
我在这做错了什么?
counter = 0
def increment():
counter += 1
increment()
Run Code Online (Sandbox Code Playgroud)
上面的代码抛出了一个UnboundLocalError.
我正在阅读有关Python 全局语句("Python范围")的问题,我记得当我是Python初学者时我经常使用这个语句(我使用全局))以及如何,如今,多年后,我不知道永远不要使用它.我甚至认为它有点"非pythonic".
你在Python中使用这个语句吗?您对它的使用是否随时间而变化?
假设我有以下python代码:
def outer():
string = ""
def inner():
string = "String was changed by a nested function!"
inner()
return string
Run Code Online (Sandbox Code Playgroud)
我想调用outer()来返回"String被嵌套函数改变了!",但我得到了"".我得出结论,Python认为该行string = "string was changed by a nested function!"是对inner()本地新变量的声明.我的问题是:如何告诉Python它应该使用outer()字符串?我不能使用global关键字,因为字符串不是全局的,它只是在外部范围内.想法?
Python 范围 我有同样的问题,但略有不同。
number = 0
def incrementNumber():
number += 1
Run Code Online (Sandbox Code Playgroud)
上面的这个不起作用,但下面的这个为什么?两者都在函数范围之外。
number = {'num':0}
def incrementNumber():
number['num'] += 1
Run Code Online (Sandbox Code Playgroud)
如果我将变量添加为全局变量,则第一个有效
number = 0
def incrementNumber():
global number
number += 1
Run Code Online (Sandbox Code Playgroud) 我已经阅读了其他一些SO(PythonScope和全局变量不需要全局),但似乎没有任何内容可以像我想的那样明确解释,而且我在精神上筛选PyDocs是否告诉我问题的答案时遇到了麻烦:
myList = [1]
def foo():
myList = myList + [2, 3]
def bar():
myList.extend([2, 3])
def baz():
myList += [2, 3]
Run Code Online (Sandbox Code Playgroud)
现在,可以理解,
>>> foo()
UnboundLocalError
Run Code Online (Sandbox Code Playgroud)
和
bar() # works
myList # shows [1, 2, 3]
Run Code Online (Sandbox Code Playgroud)
但是之后
>>> baz()
UnboundLocalError
Run Code Online (Sandbox Code Playgroud)
然而,我认为,+=在这种情况下extend(),隐含地称为方法运算符的东西,但错误意味着由于某种原因它实际上不会被+=视为extends().这与Python解析应该如何工作一致吗?
我本以为调用与方法运算符等效的函数,它们在所有情况下都是等价的.相反,它似乎将其视为+=实际的赋值运算符.除此之外,这并不完全正确,因为如果我做了某些事情(诚然做作):
myList = range(50000000) # wait a second or two on my laptop before returning
myList += [0] # returns instantly
myList = …Run Code Online (Sandbox Code Playgroud) 嘿伙计们,我遇到了从argpars调用函数的问题.这是我的脚本的简化版本,这是有效的,打印我给-s或-p的任何值
import argparse
def main():
parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three octets of the class C network to scan for live hosts')
parser.add_argument("-p", dest='ip', action='store',help='conduct a portscan of specified host')
args = parser.parse_args()
print args.ip3octets
print args.ip
然而,这对我来说在逻辑上相同会产生错误:
import argparse
def main():
parser = argparse.ArgumentParser(description="Do you wish to scan for live hosts or conduct a port scan?")
parser.add_argument("-s", dest='ip3octets', action='store', help='Enter the first three … 我已经开始自学python,并且注意到与全局变量和范围有关的某些奇怪事情。当我运行这个:
x = 2
y = 3
z=17
def add_nums():
y = 6
return z+y
Run Code Online (Sandbox Code Playgroud)
打印结果为23 ...但是,当我将返回值扩展为:
x = 2
y = 3
z=17
def add_nums():
y = 6
z = z + y
return z
Run Code Online (Sandbox Code Playgroud)
我在第6行收到以下错误:
Local name referenced but not bound to a value.
A local name was used before it was created. You need to define the
method or variable before you try to use it.
Run Code Online (Sandbox Code Playgroud)
我很困惑为什么我在这里遇到错误,因为z是全局可访问的。
使用以下示例代码:
mat = []
x = 5
def add(c,b):
print c+b
x = 8
mat.append(c)
mat.append(b)
add(5,6)
add(8,9)
print mat
print x
Run Code Online (Sandbox Code Playgroud)
mat是附加但为什么不是x改变?为什么python以不同的方式处理列表和变量?