关于python:如何检查变量是否为空empty?

How to check whether a variable is empty?

本问题已经有最佳答案,请猛点这里访问。
1
2
3
4
5
6
7
8
9
10
11
12
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。主机名值来自另一个程序,有时不来自


如果没有这样的属性,您将提供一个空间作为ankit的值,但要检查None。始终如一:

1
2
3
ankit = getattr(dheepak,"hostname", None)
if ankit is None:
   ...

1
2
3
ankit = getattr(dheepak,"hostname", ' ')
if ankit == ' ':
   ...

更好的是,不要试图定义一个sentinel值;只需捕获getattr在属性不存在时引发的异常。

1
2
3
4
5
6
try:
    ankit = getattr(dheepak,"hostname")
except AttributeError:
    print"Shanaya"
else:
    print"byee"


这个怎么样?

1
2
3
4
5
6
7
8
9
10
11
12
class dheepak():
    age = 23
    name ="dheepak sasi"

ankit = getattr(dheepak,"hostname", '')
if not ankit:
    print"Shanaya"
else:
    print"byee"
mani = dheepak.age

print ankit