Python資料類別 – Let’s Go!
資料類別
資料類別 | ⼤⼩ | 數值範圍 | 例⼦ |
int | def byte_length(i): return (i.bit_length() + 7) // 8 print(byte_length(1)) # 1 bytes print(byte_length(1111)) # 2 bytes print(byte_length(1111111)) # 3 bytes print(byte_length(1111111111)) # 4 bytes | int(‘999’) # 999 | |
long (當int variable overflow) | 無限 | #Python3.x long(‘999’) #999L | |
float | 小數點“浮動”: 容納不同數量的有效數字 | 支持兩種類型: 單精度:1個符號位、8個指數位、23個尾數位 雙精度:1 個符號位、11 個指數位、52 個尾數位 | float(21.33) # 21.33 |
str | 每個最少字元1 byte print(len(‘A’.encode(‘utf-16’))) #4 bytes print(len(‘A’.encode(‘utf-8’))) #1 bytes print(len(‘人’.encode(‘utf-16’))) #4 bytes print(len(‘人’.encode(‘utf-8’))) #3 bytes | str(‘Hello World’) #’Hello World’ | |
bool | 1 bit | 對錯: 只有 true 及 false 兩個值 | bool(0) #False bool(“False”) #True |
轉換值
資料類別 | 轉換公式 | 例⼦ |
int | converted_num = int (num) converted_num = int (str) | str = “4” converted_str = int( str) print(converted_str) #4 |
long | # Python2.x converted_num = long (num) converted_num = # Python3.x converted_num = int (num) converted_num = int (str) | str = “4444444” converted_str = long( str) # Python2.x converted_str = int( str) # Python3.x print(converted_str) # 4444444 |
float |
| str = “4.652” converted_str = float( str) print(converted_ str )# 4.652 |
bool | converted_num = bool(num) converted_num = bool(str) | bn = ‘true’ converted_str = bool( bn) print(converted_ str ) # True |
String | converted_str = int(str) converted_str = long(str) converted_str = float(str) converted_str = bool(str) | num = int(“4”) converted_num = str(num) print(converted_num) # 4 num = float(4.7) converted_num = str(num) print(converted_num) # 4.7 num = bool(1) converted_num = str(num) print(converted_num) #1 |
其他
自製 “constant” – 這意味著不可更改和只讀 def constant(f): def fset(self, value): raise TypeError def fget(self): return f() return property(fget, fset) class _car(object): @constant def oil(): return 40 CONST = _car() print(CONST.oil) #40 | Static Keyword static關鍵字屬於類而不是類的實例。 你能通過類直接CALL, 而不能, 也不用類的Instance Call. class test: x = 100 print(test.x) # OK |
Global, Local scope | |
Class test: engineOil = 20; #Global scope def Run(speed): #Local scope expense = engineOil * speed | Global scope variable – speed 能在Class 內調用, run方法內外調用都能 Local scope variable – engineOil, speed 不能在run方法外調用 |