国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > 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            
發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 浠水县| 普安县| 江陵县| 宁津县| 扎囊县| 长治市| 洪湖市| 什邡市| 若尔盖县| 柘荣县| 微山县| 怀安县| 沿河| 微山县| 涡阳县| 正宁县| 银川市| 黄石市| 赤城县| 安庆市| 万源市| 磐石市| 五寨县| 沁水县| 库伦旗| 仙居县| 长沙县| 英山县| 鄄城县| 丰城市| 武清区| 邯郸市| 古浪县| 华坪县| 瓮安县| 新竹县| 辽宁省| 谢通门县| 姜堰市| 富裕县| 龙井市|