4

如何判断一个变量是否被定义

 2 years ago
source link: https://ipotato.me/article/1
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

如何判断一个变量是否被定义

2012-08-21

今天闲来无事,研究Python中,突然有一想法,能否判断一个变量是否被定义,如果被未定义,则给它赋值1,于是尝试:

a = a if a is not None else 1

结果报错了,Python中不允许未被定义的变量进行a=a这样的语句,也许可以利用这一特性,用try: except:来捕获异常:

try:
    a = a
except:
    a = 1

当a未被定义时,a=a会抛出一个异常(说明a未被定义),捕获异常后,赋值1

后来,whtsky又提供了另一种方法

a = locals().get("a", "1")

locals()会返回所有的局部变量(一个字典),可以判断a是否在其中。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK