zoukankan      html  css  js  c++  java
  • python中的none

    None是一个对象,其类型为NoneType,其bool值为false,好比0是一个对象,其类型为int,其bool值为false,而在Python中bool值为false的有以下几种:

    作者:灵剑

    链接:https://www.zhihu.com/question/48707732/answer/112233903
    来源:知乎
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

    这个其实在Python文档当中有写了,为了准确起见,我们先引用Python文档当中的原文:
    In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true. (See the __nonzero__() special method for a way to change this.)

    进行逻辑判断(比如if)时,Python当中等于False的值并不只有False一个,它也有一套规则。对于基本类型来说,基本上每个类型都存在一个值会被判定为False。大致是这样:
    1. 布尔型,False表示False,其他为True
    2. 整数和浮点数,0表示False,其他为True
    3. 字符串和类字符串类型(包括bytes和unicode),空字符串表示False,其他为True
    4. 序列类型(包括tuple,list,dict,set等),空表示False,非空表示True
    5. None永远表示False

    自定义类型的对象则服从下面的规则:

    1. 如果定义了__nonzero__()方法,会调用这个方法,并按照返回值判断这个对象等价于True还是False
    2. 如果没有定义__nonzero__方法但定义了__len__方法,会调用__len__方法,当返回0时为False,否则为True(这样就跟内置类型为空时对应False相同了)
    3. 如果都没有定义,所有的对象都是True,只有None对应False
     1 >>> class a:
     2     def __nonzero__(self):
     3         return 0
     4 
     5     
     6 >>> b = a()
     7 >>> if b:
     8     print "haha"
     9 
    10     
    11 >>> if not b:
    12     print "haha"
    13 
    14     
    15 haha
    16 >>> if a:
    17     print "haha"
    18 
    19     
    20 haha

    所以准确来说,你的这句(state是字典,get方法是判断字典中的键中有没有第一个参数,没有返回第二个参数)

    state = states.get'texas'Noneif not state:
        ....
    

    等价于

    if 'texas' not in states or states['texas'] is None or not states['texas']:
        ...
    

    它有三种成立的情况:

    1. dict中不存在
    2. dict中存在,但值是None
    3. dict中存在而且也不是None,但是是一个等同于False的值,比如说空字符串或者空列表。
     
  • 相关阅读:
    More than 100 ABAP Interview Faq's
    SAP所有模块用户出口(User Exits)
    机器巡检基本知识
    SAP常用词汇
    ERP系统模块完全解析──工作中心
    abap基础
    topas命令详解
    企业如何处理制度、ISO质量体系与ERP系统的冲突
    在ALV表格中双击某一行记录后,显示明细记录
    Linux 命令修改图片尺寸!
  • 原文地址:https://www.cnblogs.com/saolv/p/8277492.html
Copyright © 2011-2022 走看看