如何检查变量是否为空?
问题描述:
class dheepak():
age = 23
name = "dheepak sasi"
ankit = getattr(dheepak, "hostname", ' ')
if ankit == None:
print "Shanaya"
else:
print "byee"
mani = dheepak.age
print ankit
如果主机名不存在,它应该打印Shanaya如果主机名存在比打印byee。和主机名值从另外一个程序来有时说到有时不如何检查变量是否为空?
答
如何:
class dheepak():
age = 23
name = "dheepak sasi"
ankit = getattr(dheepak, "hostname", '')
if not ankit:
print "Shanaya"
else:
print "byee"
mani = dheepak.age
print ankit
答
您提供一个空间为ankit
的值,如果没有这样的属性,但检查None
。是一致的:
ankit = getattr(dheepak, "hostname", None)
if ankit is None:
...
或
ankit = getattr(dheepak, "hostname", ' ')
if ankit == ' ':
...
更重要的是,不要试图在所有定义的标记值;只要在该属性不存在时捕获由getattr
引发的异常。
try:
ankit = getattr(dheepak, "hostname")
except AttributeError:
print "Shanaya"
else:
print "byee"
+0
因为他们并不需要的属性值,' hasattr'可能更合适。 –
+0
我还没有对Python 3做过多的讨论,所以我仍然避免'hasattr'。 https://hynek.me/articles/hasattr/ – chepner
或者http://stackoverflow.com/questions/9926446/how-to-check-whether-a-strvariable-is-empty-or-not –