您当前的位置: 首页 >  Python

IT之一小佬

暂无认证

  • 0浏览

    0关注

    1192博文

    0收益

  • 0浏览

    0点赞

    0打赏

    0留言

私信
关注
热门博文

python中if x 和if x is not None的区别用法详解

IT之一小佬 发布时间:2022-07-25 22:40:24 ,浏览量:0

注意:以下两种写法是有区别的。

  • if x 和 if x is not None
  • if not x 和 if x is None

        python里面的其他值也被检测为False。最常见的例子就是空列表,bool([])也返回False。但是,空列表有一个隐含的意思,它不等于None!!None意味着没有值,而空列表意味着零个值,这在语义上是不同的!

示例代码1:

x = None

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

 示例代码2:  【空列表不等于None】【python会自动给非boolean类型进行bool判断的时候转换成boolean类型

x = []

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

示例代码3:

# x = [0]
x = [1]  # 这儿写0和1是一样的

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

 示例代码4:

x = 0

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

示例代码5:

x = 1

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

示例代码6:  【自定义类】【x是被__bool__初始化的】

class Foo(object):
    def __bool__(self):
        print("Foo将会被检测为Boolean类型")
        return True


x = Foo()

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

示例代码7:

class Foo(object):
    def __bool__(self):
        print("Foo将会被检测为Boolean类型")
        return False


x = Foo()

print('test1' + '-' * 50)
if x:
    print('if x')

print('test2' + '-' * 50)
if x is not None:
    print('if x is not None')

print('test3' + '-' * 50)
if not x:
    print('if x')

print('test4' + '-' * 50)
if x is None:
    print('if x is not None')

print('test5' + '-' * 50)
print(bool(x))

运行结果:

关注
打赏
1665675218
查看更多评论
立即登录/注册

微信扫码登录

0.0431s