问题:是否只能在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

Duplicate

Related


回答 0

为什么不这样做:

var = None

Python是动态的,因此您无需声明任何东西。它们自动存在于分配它们的第一个范围中。因此,您只需要一个如上所述的常规旧赋值语句即可。

很好,因为您永远不会以未初始化的变量结尾。但是要小心-这并不意味着您最终不会得到错误初始化的变量。如果您将初始化为None,请确保这是您真正想要的,并尽可能分配更有意义的内容。

Why not just do this:

var = None

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.


回答 1

我衷心建议您阅读其他语言的“变量”(我将其添加为相关链接)–在两分钟内,您将知道Python具有“名称”,而不是“变量”。

val = None
# ...
if val is None:
   val = any_object

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”.

val = None
# ...
if val is None:
   val = any_object

回答 2

在Python 3.6+中,您可以为此使用变量注释:

https://www.python.org/dev/peps/pep-0526/#abstract

PEP 484引入了类型提示,也就是类型注释。尽管它的主要焦点是函数注释,但它也引入了类型注释的概念来注释变量:

# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str

PEP 526旨在向Python添加语法来注释变量的类型(包括类变量和实例变量),而不是通过注释来表示它们:

captain: str  # Note: no initial value!

似乎更符合您的要求:“是否有可能只声明变量而不在Python中分配任何值?”

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:

# 'captain' is a string (Note: initial value is a problem)
captain = ...  # type: str

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:

captain: str  # Note: no initial value!

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?”


回答 3

我不确定您要做什么。Python是一种非常动态的语言。在实际分配或使用变量之前,通常不需要声明变量。我想你要做的就是

foo = None

它将把值None赋给变量foo

编辑:您似乎真正想做的就是:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

从如此简短的代码示例中很难分辨出这是否是正确的样式,但这一种更加“ Pythonic”的工作方式。

编辑:以下是JFS的注释(发布在此处以显示代码)

与OP的问题无关,但以上代码可以重写为:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

注意:如果some_condition()引发异常,则found没有约束。
注意:如果len(sequence)== 0,则item表示未绑定。

上面的代码不建议使用。其目的是说明局部变量的工作方式,即在这种情况下只能在运行时确定“变量”是否为“定义”。首选方式:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

要么

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(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

foo = None

which will assign the value None to the variable foo.

EDIT: What you really seem to want to do is just this:

#note how I don't do *anything* with value here
#we can just start using it right inside the loop

for index in sequence:
   if conditionMet:
       value = index
       break

try:
    doSomething(value)
except NameError:
    print "Didn't find anything"

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:

for item in sequence:
    if some_condition(item): 
       found = True
       break
else: # no break or len(sequence) == 0
    found = False

if found:
   do_something(item)

NOTE: if some_condition() raises an exception then found 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:

for item in sequence:
    if some_condition(item):
       do_something(item)
       break

Or

found = False
for item in sequence:
    if some_condition(item):
       found = True
       break

if found:
   do_something(item)

回答 4

我通常将变量初始化为某种表示类型的东西

var = ""

要么

var = 0

如果它将成为对象,那么在实例化它之前不要对其进行初始化:

var = Var()

I usually initialize the variable to something that denotes the type like

var = ""

or

var = 0

If it is going to be an object then don’t initialize it until you instantiate it:

var = Var()

回答 5

好吧,如果您想检查是否定义了变量,那为什么不检查它是否在locals()或globals()数组中呢?您的代码被重写:

for index in sequence:
   if 'value' not in globals() and conditionMet:
       value = index
       break

如果它是您要查找的局部变量,则将locals()替换为globals()。

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:

for index in sequence:
   if 'value' not in globals() and conditionMet:
       value = index
       break

If it’s a local variable you are looking for then replace globals() with locals().


回答 6

首先,我对您最初提出的问题的回答

问:如何查找是否在代码中的某个点定义了变量?

答:在源文件中读取,直到看到定义该变量的行。

但是,此外,您还给出了一个代码示例,其中的各种排列都是pythonic的。您正在寻找一种扫描序列以查找与条件匹配的元素的方法,因此这里有一些解决方案:

def findFirstMatch(sequence):
    for value in sequence:
        if matchCondition(value):
            return value

    raise LookupError("Could not find match in sequence")

显然,在此示例中,您可以根据要实现的目标raise用替换return None

如果您想要满足条件的所有内容,则可以执行以下操作:

def findAllMatches(sequence):
    matches = []
    for value in sequence:
        if matchCondition(value):
            matches.append(value)

    return matches

还有另一种方法yield,我不会麻烦您看,因为它的工作方式非常复杂。

此外,有一种方法可以实现此目的:

all_matches = [value for value in sequence if matchCondition(value)]

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:

def findFirstMatch(sequence):
    for value in sequence:
        if matchCondition(value):
            return value

    raise LookupError("Could not find match in sequence")

Clearly in this example you could replace the raise with a return None depending on what you wanted to achieve.

If you wanted everything that matched the condition you could do this:

def findAllMatches(sequence):
    matches = []
    for value in sequence:
        if matchCondition(value):
            matches.append(value)

    return matches

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:

all_matches = [value for value in sequence if matchCondition(value)]

回答 7

如果我理解您的示例正确,那么无论如何您都无需在if语句中引用“值”。只要将其设置为任何值,您就可以摆脱循环。

value = None
for index in sequence:
   doSomethingHere
   if conditionMet:
       value = index
       break 

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.

value = None
for index in sequence:
   doSomethingHere
   if conditionMet:
       value = index
       break 

回答 8

您似乎正在尝试用Python编写C。如果您想按顺序查找某物,Python提供了内置函数来实现,例如

value = sequence.index(blarg)

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

value = sequence.index(blarg)

回答 9

这是一个好问题,不幸的var = None是,答案很差,因为已经分配了一个值,并且如果您的脚本多次运行,则None每次都会覆盖它。

它与没有分配的定义不同。我仍在尝试找出如何绕过此问题的方法。

It is a good question and unfortunately bad answers as var = None is already assigning a value, and if your script runs multiple times it is overwritten with None every time.

It is not the same as defining without assignment. I am still trying to figure out how to bypass this issue.


回答 10

是否可以在Python中声明变量(var = None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var

Is it possible to declare a variable in Python (var=None):

def decl_var(var=None):
if var is None:
    var = []
var.append(1)
return var

回答 11

var_str = str()
var_int = int()
var_str = str()
var_int = int()

回答 12

如果None是一个有效的数据值,那么您需要使用另一种方式来变量。您可以使用:

var = object()

尼克·科格兰Nick Coghlan)建议这个哨兵。

If None is a valid data value then you need to the variable another way. You could use:

var = object()

This sentinel is suggested by Nick Coghlan.


回答 13

您可以使用此丑陋的oneliner欺骗解释器。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.


声明:本站所有文章,如无特殊说明或标注,均为本站原创发布。任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站、书籍等各类媒体平台。如若本站内容侵犯了原著者的合法权益,可联系我们进行处理。