前言
大家都知道python内置的常量不多,只有6个,分别是true、false、none、notimplemented、ellipsis、debug。下面就来看看详细的介绍:
一. true
1. true是bool类型用来表示真值的常量。
>>> true true >>> type(true) <class 'bool'>
2. 对常量true进行任何赋值操作都会抛出语法错误。
>>> true = 1 syntaxerror: can't assign to keyword
二. false
1. false是bool类型用来表示假值的常量。
>>> false false >>> type(false) <class 'bool'>
2. 对常量false进行任何赋值操作都会抛出语法错误。
>>> false = 0 syntaxerror: can't assign to keyword
三. none
1. none表示无,它是nonetype的唯一值。
>>> none #表示无,没有内容输出 >>> type(none) <class 'nonetype'>
2. 对常量none进行任何赋值操作都会抛出语法错误。
>>> none = 2 syntaxerror: 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类型的常量。
>>> notimplemented notimplemented >>> 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 == a2 self: tom 1 other: jay 1 true
>>> 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 == a2 self: tom 1 other: jay 1 self: jay 1 other: tom 1 false
当执行a1==a2(即调用eq(a1,a2)),返回notimplemented时,python会自动交换参数再次调用eq(a2,a1)。
五. ellipsis
1. ellipsis是ellipsis类型的常量,它和…是等价的。
>>> ellipsis ellipsis >>> type(ellipsis) <class 'ellipsis'> >>> ... ellipsis >>> ... == ellipsis true
2. 使用bool()函数进行测试可以发现,ellipsis是一个真值。
>>> bool(ellipsis) true
3. ellipsis不是一个绝对意义上的常量,因为他可以被赋值却不会抛出语法错误,我们也不应该去对其赋值,否则会影响程序的执行结果。
>>> bool(ellipsis) true >>> ellipsis = false >>> bool(ellipsis) false
4. ellipsis多用于表示循环的数据结构。
>>> a = [1,2,3,4] >>> a.append(a) >>> a [1, 2, 3, 4, [...]] >>> a [1, 2, 3, 4, [...]] >>> len(a) >>> a[4] [1, 2, 3, 4, [...]] >>>
六. debug
1. debug是一个bool类型的常量。
>>> debug true >>> type(debug) <class 'bool'>
2. 对常量debug进行任何赋值操作都会抛出语法错误。
>>> debug = false syntaxerror: assignment to keyword
3. 如果python没有使用-o选项启动,此常量是真值,否则是假值。
总结
以上就是python中内置常量的深入理解的详细内容。
