在Python中是否可以只声明一个变量而不分配任何值?
是否可以在Python中声明一个变量,像这样?:
var
以便它初始化为None? 看起来Python允许这样做,但是一旦你访问它,它就会崩溃。 这可能吗? 如果没有,为什么?
编辑:我想对这样的情况执行此操作:
value
for index in sequence:
if value == None and conditionMet:
value = index
break
相关问题
另请参阅
Is it possible to declare a variable in Python, like so?:
var
so that it initialized to None? It seems like Python allows this, but as soon as you access it, it crashes. Is this possible? If not, why?
EDIT: I want to do this for cases like this:
value
for index in sequence:
if value == None and conditionMet:
value = index
break
Related Questions
- Why can a function modify some arguments as perceived by the caller, but not others?
- Python Variable Declaration
See Also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(14)
在 Python 3.6+ 中,您可以使用变量注释来实现此目的:
https://www. python.org/dev/peps/pep-0526/#abstract
PEP 484 引入了类型提示,又名类型注释。 虽然它的主要焦点是函数注释,但它还引入了类型注释的概念来注释变量:
PEP 526 旨在向 Python 添加用于注释变量类型(包括类变量和实例变量)的语法,而不是通过注释来表达它们:
它似乎更直接地符合你所问的问题“在Python中是否可以只声明一个变量而不分配任何值?”
注意:Python 运行时不强制执行函数和变量类型注释。 它们可以被第三方工具使用,例如类型检查器、IDE、linter 等。
In Python 3.6+ you could use Variable Annotations for this:
https://www.python.org/dev/peps/pep-0526/#abstract
PEP 484 introduced type hints, a.k.a. type annotations. While its main focus was function annotations, it also introduced the notion of type comments to annotate variables:
PEP 526 aims at adding syntax to Python for annotating the types of variables (including class variables and instance variables), instead of expressing them through comments:
It seems to be more directly in line with what you were asking "Is it possible only to declare a variable without assigning any value in Python?"
Note: The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.
我衷心建议您阅读 其他语言有“变量”(我将其添加为相关链接)——两分钟内你就会知道 Python 有“名称”,而不是“变量”。
I'd heartily recommend that you read Other languages have "variables" (I added it as a related link) – in two minutes you'll know that Python has "names", not "variables".
我不确定你想做什么。 Python 是一种非常动态的语言; 在实际要赋值或使用变量之前,通常不需要声明变量。 我认为您想要做的就是
将值
None
分配给变量foo
。编辑:您真正似乎想做的就是这样:
从这么短的代码示例中判断这是否真的是正确的样式有点困难,但它是 一种更“Pythonic”的工作方式。
编辑:下面是JFS的评论(在这里发布以显示代码)
与OP的问题无关,但上面的代码可以重写为:
注意:如果
some_condition()
引发异常,则found
未绑定。注意:如果 len(sequence) == 0 则
item
未绑定。上面的代码是不可取的。 其目的是说明局部变量如何工作,即在这种情况下只能在运行时确定“变量”是否“定义”。
首选方式:
或者
I'm not sure what you're trying to do. Python is a very dynamic language; you don't usually need to declare variables until you're actually going to assign to or use them. I think what you want to do is just
which will assign the value
None
to the variablefoo
.EDIT: What you really seem to want to do is just this:
It's a little difficult to tell if that's really the right style to use from such a short code example, but it is a more "Pythonic" way to work.
EDIT: below is comment by JFS (posted here to show the code)
Unrelated to the OP's question but the above code can be rewritten as:
NOTE: if
some_condition()
raises an exception thenfound
is unbound.NOTE: if len(sequence) == 0 then
item
is unbound.The above code is not advisable. Its purpose is to illustrate how local variables work, namely whether "variable" is "defined" could be determined only at runtime in this case.
Preferable way:
Or
好吧,如果你想检查一个变量是否已定义,那么为什么不检查它是否在 locals() 或 globals() 数组中呢? 重写您的代码:
如果您要查找的是局部变量,则将 globals() 替换为 locals()。
Well, if you want to check if a variable is defined or not then why not check if its in the locals() or globals() arrays? Your code rewritten:
If it's a local variable you are looking for then replace globals() with locals().
我知道它来晚了,但是对于 python3,你可以使用声明一个未初始化的值,
但是要非常小心这个技巧,因为
I know it's coming late but with python3, you can declare an uninitialized value by using
But be very careful with this trick tho, because
我通常将变量初始化为表示类型的东西,例如
或
如果它将是一个对象,那么在实例化它之前不要初始化它:
I usually initialize the variable to something that denotes the type like
or
If it is going to be an object then don't initialize it until you instantiate it:
首先,我对您最初提出的问题的回答
问:如何发现变量是否在代码中的某个点定义?
答:在源文件中阅读直到您看到定义该变量的行。
但更进一步,您已经给出了一个代码示例,其中有各种排列,这些排列非常Pythonic。 您正在寻找一种扫描序列以查找与条件匹配的元素的方法,因此这里有一些解决方案:
显然,在此示例中,您可以将
raise
替换为return None
取决于您想要实现的目标。如果您想要与条件匹配的所有内容,您可以这样做:
还有另一种使用
yield
执行此操作的方法,我不会费心向您展示,因为它的工作方式相当复杂。此外,还有一种单行方法可以实现这一目标:
First of all, my response to the question you've originally asked
Q: How do I discover if a variable is defined at a point in my code?
A: Read up in the source file until you see a line where that variable is defined.
But further, you've given a code example that there are various permutations of that are quite pythonic. You're after a way to scan a sequence for elements that match a condition, so here are some solutions:
Clearly in this example you could replace the
raise
with areturn None
depending on what you wanted to achieve.If you wanted everything that matched the condition you could do this:
There is another way of doing this with
yield
that I won't bother showing you, because it's quite complicated in the way that it works.Further, there is a one line way of achieving this:
如果我正确理解您的示例,那么您无论如何都不需要在 if 语句中引用“值”。 一旦它可以设置为任何值,您就可以跳出循环。
If I'm understanding your example right, you don't need to refer to 'value' in the if statement anyway. You're breaking out of the loop as soon as it could be set to anything.
如果
None
是有效的数据值,那么您需要以另一种方式访问该变量。 您可以使用:此哨兵是由 Nick Coghlan 建议的。
If
None
is a valid data value then you need to the variable another way. You could use:This sentinel is suggested by Nick Coghlan.
是否可以在Python中声明一个变量(var=None):
Is it possible to declare a variable in Python (var=None):
你看起来像是在尝试用 Python 编写 C 语言。 如果你想在序列中查找某些内容,Python 有内置函数可以做到这一点,例如
You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like
你可以用这个丑陋的单行代码来欺骗解释器
if None: var = None
它除了将变量 var 添加到局部变量字典中而不是初始化它之外什么也不做。 如果您随后尝试在函数中使用此变量,解释器将抛出 UnboundLocalError 异常。 这也适用于非常古老的 python 版本。 不简单,也不美观,但不要对 python 抱有太大期望。
You can trick an interpreter with this ugly oneliner
if None: var = None
It do nothing else but adding a variable
var
to local variable dictionary, not initializing it. Interpreter will throw the UnboundLocalError exception if you try to use this variable in a function afterwards. This would works for very ancient python versions too. Not simple, nor beautiful, but don't expect much from python.为什么不这样做呢:
Python 是动态的,所以你不需要声明东西; 它们自动存在于分配它们的第一个范围中。 因此,您所需要的只是如上所述的常规旧赋值语句。
这很好,因为您永远不会得到未初始化的变量。 但要小心——这并不意味着您不会最终得到错误初始化的变量。 如果您将某些内容初始化为
None
,请确保这是您真正想要的内容,并尽可能分配更有意义的内容。Why not just do this:
Python is dynamic, so you don't need to declare things; they exist automatically in the first scope where they're assigned. So, all you need is a regular old assignment statement as above.
This is nice, because you'll never end up with an uninitialized variable. But be careful -- this doesn't mean that you won't end up with incorrectly initialized variables. If you init something to
None
, make sure that's what you really want, and assign something more meaningful if you can.