Built_in(s)
1.Type and Classes
- bool, int, float, str, list, tuple, dict, set關(guān)鍵字的屬性都是type
- set不能為空,{}內(nèi)至少要有一個元素,比如{1}
-
bool是int的子類,且不可以再子類化,bool < int < object。為什么bool是int的子類?因為一個bool是只可以取兩個值的int,但它比實際的整數(shù)的運算/空間要少,bool型只有很少的存儲空間。
所以可以用0表示false,非0的數(shù)表示true。同時bool支持?jǐn)?shù)學(xué)運算。Python 2.x的時候True和False還沒固定值,但到了Python 3.x的時候True已經(jīng)default為1,F(xiàn)alse為0。
bool(0)
>>> False
bool(1.2) + bool(-1.2)
>>> 2
coding使用isinstance()作為判別條件的時候,要小心:
isinstance(True, bool) --> True
isinstance(False, bool) --> True
isinstance(True, int) --> True
isinstance(False, int) --> True
2.Literal Representation
- bool型false包括None和void,比如bool(None), bool({})
- int()類型轉(zhuǎn)換浮點數(shù)時不是四舍五入,而是斷尾,比如int(17.9) = 17。如果想實現(xiàn)四舍五入,可以使用int(x + 0.5),這樣int(17.9+0.5) = 18, int(17.3+0.5) = 17
- 常見進制開頭,二進制0b/B,八進制0o/O,十六進制0x/X
- 復(fù)數(shù)表達:complex([real[, imag]]),其中real可以是int, float, str,imag可以是int, float。如果real是str,則不能輸入imag。取值實數(shù)部分在復(fù)數(shù)后面加.real,取值虛數(shù)部分在復(fù)數(shù)后面加.imag,注意無論實數(shù)和虛數(shù)位是int還是float型,取得的real和imag都是float型。
共軛復(fù)數(shù)在復(fù)數(shù)后面加.conjugate()
complex("2")
>>> 2+0j
complex("2+3j") #字符串中+前后不能有空格
>>>2+3j
complex(2.3, 2.3)
>>>2.3+2.3j
complex(1, 2).conjugate()
>>>1-2j
complex(1, 2.1).real
>>>1.0
complex(2.1, 2).imag
>>>2.0
Nonlocal. Nonlocal is similar in meaning to global. But it takes effect primarily in nested methods. It means "not a global or local variable." So it changes the identifier to refer to an enclosing method's variable.