首页 > 编程 > Python > 正文

深入理解Python中的内置常量

2020-02-16 01:33:29
字体:
来源:转载
供稿:网友

前言

大家都知道Python内置的常量不多,只有6个,分别是True、False、None、NotImplemented、Ellipsis、__debug__。下面就来看看详细的介绍:

一. True

1. True是bool类型用来表示真值的常量。

>>> TrueTrue>>> type(True)<class 'bool'>

2. 对常量True进行任何赋值操作都会抛出语法错误。

>>> True = 1SyntaxError: can't assign to keyword

二. False

1. False是bool类型用来表示假值的常量。

>>> FalseFalse>>> type(False)<class 'bool'>

2. 对常量False进行任何赋值操作都会抛出语法错误。

>>> False = 0SyntaxError: can't assign to keyword

三. None

1. None表示无,它是NoneType的唯一值。

>>> None #表示无,没有内容输出>>> type(None)<class 'NoneType'>

2. 对常量None进行任何赋值操作都会抛出语法错误。

>>> None = 2SyntaxError: can't assign to keyword

3. 对于函数,如果没有return语句,即相当于返回None。

>>> def sayHello(): #定义函数 print('Hello') >>> sayHello()Hello>>> result = sayHello()Hello>>> result>>> type(result)<class 'NoneType'>

四. NotImplemented

1.  NotImplemented是NotImplementedType类型的常量。

>>> NotImplementedNotImplemented>>> type(NotImplemented)<class 'NotImplementedType'>

2. 使用bool()函数进行测试可以发现,NotImplemented是一个真值。

>>> bool(NotImplemented)True

3. NotImplemented不是一个绝对意义上的常量,因为他可以被赋值却不会抛出语法错误,我们也不应该去对其赋值,否则会影响程序的执行结果。

>>> bool(NotImplemented)True>>> NotImplemented = False>>> >>> bool(NotImplemented)False

4. NotImplemented多用于一些二元特殊方法(比如__eq__、__lt__等)中做为返回值,表明没有实现方法,而Python在结果返回NotImplemented时会聪明的交换二个参数进行另外的尝试。

>>> class A(object): def __init__(self,name,value):  self.name = name  self.value = value def __eq__(self,other):  print('self:',self.name,self.value)  print('other:',other.name,other.value)  return self.value == other.value #判断2个对象的value值是否相等>>> a1 = A('Tom',1)>>> a2 = A('Jay',1)>>> a1 == a2self: Tom 1other: Jay 1True
>>> class A(object): def __init__(self,name,value):  self.name = name  self.value = value def __eq__(self,other):  print('self:',self.name,self.value)  print('other:',other.name,other.value)  return NotImplemented>>> a1 = A('Tom',1)>>> a2 = A('Jay',1)>>> a1 == a2self: Tom 1other: Jay 1self: Jay 1other: Tom 1False            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表