Python3中None用法

x33g5p2x  于2021-11-06 转载在 Python  
字(0.9k)|赞(0)|评价(0)|浏览(337)

    1.None是一个空值,空值是Python里的一个特殊值,用None表示。可以将None赋值给任何变量。

  1. var = None; print(var) # None
  2. if var is None:
  3. print("var has a value of None") # print
  4. else:
  5. print("var:", var)

    2.None有自己的数据类型,它属于NoneType类型。None是NoneType数据类型的唯一值。

  1. print(type(None)) # <class 'NoneType'>

    3.None不等于空字符串、空列表、0,也不等同于False。

  1. a = ''; print(a == None) # False
  2. b = []; print(b == None) # False
  3. c = 0; print(c == None) # False
  4. d = False; print(c == None) # False

    4.None是一个特殊的空对象,可以用来占位。

  1. L = [None] * 5; print(L) # [None, None, None, None, None]

    5.对于定义的函数,如果没有return语句,在Python中会返回None;如果有不带值的return语句,那么也是返回None。

  1. def func():
  2. x = 3
  3. obj = func(); print(obj) # None
  4. def func2():
  5. return None
  6. obj2 = func2(); print(obj2) # None
  7. def func3():
  8. return
  9. obj3 = func3(); print(obj3) # None

    6.对于定义的函数,如果默认参数是一个可修改的容器如列表、集合或字典,可以使用None作为默认值。

  1. def func4(x, y=None):
  2. if y is not None:
  3. print("y:", y)
  4. else:
  5. print("y is None")
  6. print("x:", x)
  7. x = [1, 2]; obj4 = func4(x) # y is None
  8. y = [3, 4]; obj4 = func4(x, y) # y: [3, 4]

    GitHubhttps://github.com/fengbingchun/Python_Test

相关文章