是否可以只声明一个变量而不在 Python 中分配任何值? [英] Is it possible only to declare a variable without assigning any value in Python?

查看:20
本文介绍了是否可以只声明一个变量而不在 Python 中分配任何值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以像这样在 Python 中声明一个变量?:

Is it possible to declare a variable in Python, like so?:

var

所以它初始化为None?Python 似乎允许这样做,但是一旦您访问它,它就会崩溃.这可能吗?如果没有,为什么?

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?

我想针对这样的情况执行此操作:

I want to do this for cases like this:

value

for index in sequence:

   if value == None and conditionMet:
       value = index
       break

重复

  • python 中未初始化的值(同一作者)
  • Python 中是否有任何声明关键字?(由同一作者)
  • Duplicate

    • Uninitialised value in python (by same author)
    • Are there any declaration keywords in Python? (by the same author)
    • 推荐答案

      为什么不这样做:

      var = None
      

      Python 是动态的,所以你不需要声明东西;它们自动存在于分配它们的第一个作用域中.因此,您所需要的只是上面的常规旧赋值语句.

      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.

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

      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.

      这篇关于是否可以只声明一个变量而不在 Python 中分配任何值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆