python 如何在使用之前测试变量是否已初始化?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2303005/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to test whether a variable has been initialized before using it?
提问by Chris
So let's say you've got an application with a variable that you will be creating an instance of when you load it independently (ie when you use if __name__ == '__main__'
).
因此,假设您有一个带有变量的应用程序,当您独立加载它时(即当您使用 时if __name__ == '__main__'
),您将创建一个实例。
Also, there is a method that is to be called for when a client imports the application for use within another application. This method will also instantiate this variable.
此外,当客户端导入应用程序以在另一个应用程序中使用时,将调用一种方法。此方法还将实例化此变量。
What I want to do is test whether the variable has already been instantiated before defining it (so I don't have to go through the creation of the object twice). My intuition told me to use if SOME_VARIABLE is not None: #instantiate here
but this yields the error
我想要做的是在定义变量之前测试它是否已经被实例化(所以我不必两次创建对象)。我的直觉告诉我使用,if SOME_VARIABLE is not None: #instantiate here
但这会产生错误
local variable 'SOME_VARIABLE' referenced before assignment
赋值前引用的局部变量“SOME_VARIABLE”
What gives?
是什么赋予了?
回答by Matt Anderson
It's an error to access a variable before it is initialized. An uninitialized variable's value isn't None; accessing it just raises an exception.
在初始化之前访问变量是错误的。未初始化变量的值不是 None;访问它只会引发异常。
You can catch the exception if you like:
如果您愿意,可以捕获异常:
>>> try:
... foo = x
... except NameError:
... x = 5
... foo = 1
In a class, you can provide a default value of None and check for that to see if it has changed on a particular instance (assuming that None isn't a valid value for that particular variable):
在类中,您可以提供 None 的默认值并检查它是否在特定实例上发生了更改(假设 None 不是该特定变量的有效值):
class Foo(object):
bar = None
def foo(self):
if self.bar is None:
self.bar = 5
return self.bar
回答by Wim
You can try if 'varname' in locals()
(you probably also have to check globals()
, and maybe some other places), or just read from the variable and catch the NameError
exception which will be thrown when it doesn't exist.
您可以尝试if 'varname' in locals()
(您可能还必须检查globals()
,也许还需要检查其他一些地方),或者只是从变量中读取并捕获NameError
当它不存在时将抛出的异常。
But if you just want the else-case of if __name__ == '__main__'
, why not just do:
但是,如果您只想要 else 的情况if __name__ == '__main__'
,为什么不这样做:
if __name__ == '__main__'
myvar = 'as_main'
else:
myvar = 'as_import'