Python 判断变量是否已定义介绍_PHP教程
程序员文章站
2022-04-16 23:09:20
...
需要判断变量是否已经定义。在php里面这是一个轻而易举的事情,直接用isset函数判断一下变量就可以了,不过python里面好像没有这么简单。google了一下,没有好的结果,最后只好,自己动手写一个了。用的是try .. except ..else 来做到的。
仿照php,定义了一个isset函数.
def isset(v):
try :
type (eval(v))
except :
return 0
else :
return 1
def isset(v):
try:
type (eval(v))
except:
return 0
else:
return 1
def isset(v):
try:
type (eval(v))
except:
return 0
else:
return 1
当判断一个变量是否定义时候,直接调用这个函数就可以了,但是需要注意到是,必须传入一个字符串。比如,判断user_name是否定义时候,需要这样调用
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······15001.if isset( user_name ):
print user_name is defined
else
print user_name is not defined
仿照php,定义了一个isset函数.
def isset(v):
try :
type (eval(v))
except :
return 0
else :
return 1
def isset(v):
try:
type (eval(v))
except:
return 0
else:
return 1
def isset(v):
try:
type (eval(v))
except:
return 0
else:
return 1
当判断一个变量是否定义时候,直接调用这个函数就可以了,但是需要注意到是,必须传入一个字符串。比如,判断user_name是否定义时候,需要这样调用
·········10········20········30········40········50········60········70········80········90········100·······110·······120·······130·······140·······15001.if isset( user_name ):
print user_name is defined
else
print user_name is not defined