python對象的相關術語
-
python程序中保存的所有數據都是圍繞對象的概念展開的
-
程序中存儲的所有數據都是對象
-
每個對象都有一個身份、一個類型和一個值 對象的身份:
In [4]: name = 'xiangge' In [5]: id(name) Out[5]: 139851606368640
對象的類型:
In [6]: type(name) Out[6]: builtins.str
-
對象的類型決定對象可以參與的操作(可以理解成支持的函數操作),python是屬性強類型的語言。
-
創建特定類型的對象時,也可以稱該對象為該類型的事例化。
-
事例被創建后,其身份和類型就不可改變。值分兩種可變和不可變的,可變稱可變對象,如列表,字典。不可變的稱為不可變對象如字符串,元組,數字都是不可變對象。
-
某個對象包含對其他對象的引用,則將其稱為容器,如:列表。
-
大多數對象都擁有大量特有的數據屬性和方法 屬性:與對象相關的值(對象事例化時給對象內部變量賦的值) 方法:被調用時講在對象上執行某些操作的函數。 使用點()運算符可以訪問屬性和方法。
-
查詢某一種內置類型所支持的內置方法
help(類型)
兩對象的比較:
1.值比較:對象中的數據是否相同
In [7]: num1 = 5 In [8]: num2 = 5 In [9]: num1 == num2 Out[9]: True
2.身份比較:兩個變量名引用的是
In [10]: id(num1) Out[10]: 9306112 In [11]: id(num2) Out[11]: 9306112 In [12]: num1 is num2 Out[12]: True
3.類型比較:兩個對象的類型是否相同
In [13]: type(num1) is type(num2) Out[13]: True
python核心數據類型
對象的類型
- 數字:int,long,float,complex,bool
- 字符:str,unicod
- 列表:list
- 字典:dict
- 元組:tuple
- 文件:file
- 其他類型:集合(set),凍結集合(frozenset),類類型等。
類型轉換的函數: str(),repr()或format():將非字符型數據轉換成字符型
int():轉為整型
float():轉為浮點型
In [14]: str1 = '45' In [15]: type(str1) Out[15]:str In [16]: num3 =int(str1) In [19]: type(num3) Out[19]: int
list():可以將字串轉成列表
In [20]: str3 = 'xiangge' In [21]: l1 = list(str3) In [23]: print(l1) ['x', 'i', 'a', 'n', 'g', 'g', 'e'] In [24]: type(l1) Out[24]: builtins.list
tuple():將字串轉換成元組
set():將字串轉換成集合,集合沒有次序,並且把重復的都去掉。
In [20]: str3 = 'xiangge' In [25]: s1 = set(str3) In [26]: type(s1) Out[26]: set In [27]: print(s1) {'a', 'e', 'n', 'g', 'i', 'x'}
dict():轉換為字典
In [28]: l3 = [('a',1),('b',2),('c',3)] In [29]: print(l3) [('a', 1), ('b', 2), ('c', 3)] In [30]: d1 = dict(l3) In [31]: print(d1) {'a': 1, 'b': 2, 'c': 3}
chr():將整數轉為字符
ord():將字符串轉換成整數
hex():將整數轉換16進制
bin():將整數轉2進制
oct(x):將整數轉8進制
數字類型
python的數字字面量:布爾型,整數,浮點數,復數。所有數字類型均不可變。 數字操作: +,-,*,/,**,%, <<(左移位),>>(右移位),&按位與,|按位或
序列類型
序列表示索引為非負整數的有序對象集合,包括字符串、列表和元組。字符串和元組屬於不可變序列,所有序列都支持迭代。
適用所有序列的操作和方法
- s[i]: 索引運算
- s[i:j]: 為切片運算符
- s[i:j:stride]: 為擴展切片運算符
- len(s): 序列長度
- min(s) : s中最小值
- max(s):s中最大值
- sum(s): s中各項和
- all(s):檢查s中的所有項是否為True
- any(s) : 檢查s中的任意項是否為True
適用於可變序列的操作
- s[i] = v 項目賦值
- s[i:j] =t 切片賦值
- s[i:j:stride] = t 擴展切片賦值
- del s[i] 項目刪除
- del s[i:j] 切片刪除
- del s[i:j:stride] 擴展切片刪除
字符串介紹
定義:它是一個有序的字符的集合,用於存儲和表示基本的文本信息,‘’或“”或‘’‘ ’‘’中間包含的內容稱之為字符串 特性: 1.只能存放一個值 2.不可變 3.按照從左到右的順序定義字符集合,下標從0開始順序訪問,有序 補充: 1.字符串的單引號和雙引號都無法取消特殊字符的含義,如果想讓引號內所有字符均取消特殊意義,在引號前面加r,如name=r'l\thf' 2.unicode字符串與r連用必需在r前面,如name=ur'l\thf'
2.2.2.1 字符串創建
‘hello world’
2.2.2.2 字符串常用操作
移除空白 S.strip([chars]) -> str 前后空白移除
def strip(self, chars=None): # real signature unknown; restored from __doc__ """ S.strip([chars]) -> str Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead. """ return
分割
def split(self, sep=None, maxsplit=-1): # real signature unknown; restored from __doc__ """ 以sep為分割,將S切分成列表,與partition的區別在於切分結果不包含sep, 如果一個字符串中包含多個sep那么maxsplit為最多切分成幾部分 >>> a='a,b c\nd\te' >>> a.split() ['a,b', 'c', 'd', 'e'] S.split(sep=None, maxsplit=-1) -> list of strings Return a list of the words in S, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done. If sep is not specified or is None, any whitespace string is a separator and empty strings are removed from the result. """ return []
判斷字符串中是否全為數字
S.isdigit() -> bool
Return True if all characters in S are digits and there is at least one character in S, False otherwise. """ return False 如果字符串的所有字符是數字返回True,至少有一個字符字符串則返回False。 In [29]: user = '123' In [31]: user.isdigit() Out[31]: True
判斷是否全為空格
S.isspace() -> bool Return True if all characters in S are whitespace and there is at least one character in S, False otherwise. """ 如果S中的所有字符都是空格,返回True S中至少有一個字符,否則是假的。
判斷字符串是否以什么開頭
S.startswith(prefix[, start[, end]]) -> bool Return True if S starts with the specified prefix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. prefix can also be a tuple of strings to try. """ In [32]: user ='xiangge' In [33]: user.startswith('xiang') Out[33]: True
判斷字符串是否以什么結尾
def endswith(self, suffix, start=None, end=None): # real signature unknown; restored from __doc__ """ S.endswith(suffix[, start[, end]]) -> bool Return True if S ends with the specified suffix, False otherwise. With optional start, test S beginning at that position. With optional end, stop comparing S at that position. suffix can also be a tuple of strings to try. """ return False
取出字符索引
def index(self, sub, start=None, end=None): # real signature unknown; restored from __doc__ """ S.index(sub[, start[, end]]) -> int Like S.find() but raise ValueError when the substring is not found. """ return 0
列表介紹
定義:[]內以逗號分隔,按照索引,存放各種數據類型,每個位置代表一個元素 特性: 1.可存放多個值 2.可修改指定索引位置對應的值,可變 3.按照從左到右的順序定義列表元素,下標從0開始順序訪問,有序
2.2.3.1 列表創建
list_test=[’lhf‘,12,'ok'] 或 list_test=list('abc') In [9]: list_test=list('abc') In [10]: list_test Out[10]: ['a', 'b', 'c']
或 list_test=list([’lhf‘,12,'ok'])
2.2.3.2 列表常用操作
索引 list[0]
追加 L.append(object)
L.insert(index, object)
刪除 L.pop([index]) #不加參數默認刪最后一個,pop(0)刪第一個,寫操作。
長度 len(list)
切片 list[1:3] list[1:5:2]
循環
包含 in 'value' in list
其他常用: L.index(value, [start, [stop]])
extend 和 append區別 L.extend(iterable)
remove 不存在報錯,默認刪掉第一個找到的。 L.remove(value)
sort(reverse=Trun) L.sort(key=None, reverse=False)
元組介紹
定義:與列表類似,只不過[]改成() 特性: 1.可存放多個值
2.不可變
3.按照從左到右的順序定義元組元素,下標從0開始順序訪問,有序
創建元組
ages = (11, 22, 33, 44, 55) 或 ages = tuple((11, 22, 33, 44, 55))
常見操作:
class tuple(object): """ tuple() -> empty tuple tuple(iterable) -> tuple initialized from iterable's items If the argument is a tuple, the return value is the same object. """ def count(self, value): # real signature unknown; restored from __doc__ """ T.count(value) -> integer -- return number of occurrences of value """ return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__ """ T.index(value, [start, [stop]]) -> integer -- return first index of value. Raises ValueError if the value is not present. """ return 0
字典介紹
定義:{key1:value1,key2:value2},key-value結構,key必須可hash
特性:
1.可存放多個值
2.可修改指定key對應的值,可變
3.無序
字典創建
person = {"name": "sb", 'age': 18} 或 person = dict(name='sb', age=18)
person = dict({"name": "sb", 'age': 18})
person = dict((['name','sb'],['age',18]))
字典常用操作
def clear(self): # real signature unknown; restored from __doc__ """ 清除內容 """ """ D.clear() -> None. Remove all items from D. """ pass def keys(self): # real signature unknown; restored from __doc__ """ 所有的key列表 """ """ D.keys() -> list of D's keys """ return [] def pop(self, k, d=None): # real signature unknown; restored from __doc__ """ 獲取並在字典中移除 """ """ D.pop(k[,d]) -> v, remove specified key and return the corresponding value. If key is not found, d is returned if given, otherwise KeyError is raised """ pass def update(self, E=None, **F): # known special case of dict.update """ 更新 {'name':'alex', 'age': 18000} [('name','sbsbsb'),] """ """ D.update([E, ]**F) -> None. Update D from dict/iterable E and F. If E present and has a .keys() method, does: for k in E: D[k] = E[k] If E present and lacks .keys() method, does: for (k, v) in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k] """ pass def values(self): # real signature unknown; restored from __doc__ """ 所有的值 """ """ D.values() -> list of D's values """ return []
集合介紹
定義:由不同元素組成的集合,集合中是一組無序排列的可hash值,可以作為字典的key
特性: 集合的目的是將不同的值存放到一起,不同的集合間用來做關系運算,無需糾結於集合中單個值
集合創建
{1,2,3,1} 或 定義可變集合set
set_test=set('hello') set_test {'l', 'o', 'e', 'h'}
改為不可變集合frozenset
f_set_test=frozenset(set_test) f_set_test frozenset({'l', 'e', 'h', 'o'})
集合常見操作:
def discard(self, *args, **kwargs): # real signature unknown """ 移除元素 """ """ Remove an element from a set if it is a member. If the element is not a member, do nothing. """ pass def intersection(self, *args, **kwargs): # real signature unknown """ 取交集,新創建一個set """ """ Return the intersection of two or more sets as a new set. (i.e. elements that are common to all of the sets.) """ pass def intersection_update(self, *args, **kwargs): # real signature unknown """ 取交集,修改原來set """ """ Update a set with the intersection of itself and another. """ pass def isdisjoint(self, *args, **kwargs): # real signature unknown """ 如果沒有交集,返回true """ """ Return True if two sets have a null intersection. """ pass def issubset(self, *args, **kwargs): # real signature unknown """ 是否是子集 """ """ Report whether another set contains this set. """ pass def issuperset(self, *args, **kwargs): # real signature unknown """ 是否是父集 """ """ Report whether this set contains another set. """ pass def pop(self, *args, **kwargs): # real signature unknown """ 移除 """ """ Remove and return an arbitrary set element. Raises KeyError if the set is empty. """ pass def remove(self, *args, **kwargs): # real signature unknown """ 移除 """ """ Remove an element from a set; it must be a member. If the element is not a member, raise a KeyError. """ pass def symmetric_difference(self, *args, **kwargs): # real signature unknown """ 差集,創建新對象""" """ Return the symmetric difference of two sets as a new set. (i.e. all elements that are in exactly one of the sets.) """ pass def symmetric_difference_update(self, *args, **kwargs): # real signature unknown """ 差集,改變原來 """ """ Update a set with the symmetric difference of itself and another. """ pass def union(self, *args, **kwargs): # real signature unknown """ 並集 """ """ Return the union of sets as a new set. (i.e. all elements that are in either set.) """ pass def update(self, *args, **kwargs): # real signature unknown """ 更新 """ """ Update a set with the union of itself and others. """ pass
文件類型介紹
一、打開文件
1 文件句柄 = file('文件路徑', '模式') 注:python中打開文件有兩種方式,即:open(...) 和 file(...) ,本質上前者在內部會調用后者來進行文件操作,推薦使用 open。
打開文件時,需要指定文件路徑和以何等方式打開文件,打開后,即可獲取該文件句柄,日后通過此文件句柄對該文件操作。
打開文件的模式有:
-
r,只讀模式(默認)。
-
w,只寫模式。【不可讀;不存在則創建;存在則刪除內容;】
-
a,追加模式。【可讀; 不存在則創建;存在則只追加內容;】
-
"+" 表示可以同時讀寫某個文件
-
r+,可讀寫文件。【可讀;可寫;可追加】
-
w+,寫讀
-
a+,同a
-
"b"表示處理二進制文件(如:FTP發送上傳ISO鏡像文件,linux可忽略,windows處理二進制文件時需標注)
-
rb
-
wb
-
ab
二、操作操作
class file(object): def close(self): # real signature unknown; restored from __doc__ 關閉文件 """ close() -> None or (perhaps) an integer. Close the file. Sets data attribute .closed to True. A closed file cannot be used for further I/O operations. close() may be called more than once without error. Some kinds of file objects (for example, opened by popen()) may return an exit status upon closing. """ def fileno(self): # real signature unknown; restored from __doc__ 文件描述符 """ fileno() -> integer "file descriptor". This is needed for lower-level file interfaces, such os.read(). """ return 0 def flush(self): # real signature unknown; restored from __doc__ 刷新文件內部緩沖區 """ flush() -> None. Flush the internal I/O buffer. """ pass def isatty(self): # real signature unknown; restored from __doc__ 判斷文件是否是同意tty設備 """ isatty() -> true or false. True if the file is connected to a tty device. """ return False def next(self): # real signature unknown; restored from __doc__ 獲取下一行數據,不存在,則報錯 """ x.next() -> the next value, or raise StopIteration """ pass def read(self, size=None): # real signature unknown; restored from __doc__ 讀取指定字節數據 """ read([size]) -> read at most size bytes, returned as a string. If the size argument is negative or omitted, read until EOF is reached. Notice that when in non-blocking mode, less data than what was requested may be returned, even if no size parameter was given. """ pass def readinto(self): # real signature unknown; restored from __doc__ 讀取到緩沖區,不要用,將被遺棄 """ readinto() -> Undocumented. Don't use this; it may go away. """ pass def readline(self, size=None): # real signature unknown; restored from __doc__ 僅讀取一行數據 """ readline([size]) -> next line from the file, as a string. Retain newline. A non-negative size argument limits the maximum number of bytes to return (an incomplete line may be returned then). Return an empty string at EOF. """ pass def readlines(self, size=None): # real signature unknown; restored from __doc__ 讀取所有數據,並根據換行保存值列表 """ readlines([size]) -> list of strings, each a line from the file. Call readline() repeatedly and return a list of the lines so read. The optional size argument, if given, is an approximate bound on the total number of bytes in the lines returned. """ return [] def seek(self, offset, whence=None): # real signature unknown; restored from __doc__ 指定文件中指針位置 """ seek(offset[, whence]) -> None. Move to new file position. Argument offset is a byte count. Optional argument whence defaults to 0 (offset from start of file, offset should be >= 0); other values are 1 (move relative to current position, positive or negative), and 2 (move relative to end of file, usually negative, although many platforms allow seeking beyond the end of a file). If the file is opened in text mode, only offsets returned by tell() are legal. Use of other offsets causes undefined behavior. Note that not all file objects are seekable. """ pass def tell(self): # real signature unknown; restored from __doc__ 獲取當前指針位置 """ tell() -> current file position, an integer (may be a long integer). """ pass def truncate(self, size=None): # real signature unknown; restored from __doc__ 截斷數據,僅保留指定之前數據 """ truncate([size]) -> None. Truncate the file to at most size bytes. Size defaults to the current file position, as returned by tell(). """ pass def write(self, p_str): # real signature unknown; restored from __doc__ 寫內容 """ write(str) -> None. Write string str to file. Note that due to buffering, flush() or close() may be needed before the file on disk reflects the data written. """ pass def writelines(self, sequence_of_strings): # real signature unknown; restored from __doc__ 將一個字符串列表寫入文件 """ writelines(sequence_of_strings) -> None. Write the strings to the file. Note that newlines are not added. The sequence can be any iterable object producing strings. This is equivalent to calling write() for each string. """ pass def xreadlines(self): # real signature unknown; restored from __doc__ 可用於逐行讀取文件,非全部 """ xreadlines() -> returns self. For backward compatibility. File objects now include the performance optimizations previously implemented in the xreadlines module. """ pass
三、with
為了避免打開文件后忘記關閉,可以通過管理上下文,即:
with open('log','r') as f: ... 如此方式,當with代碼塊執行完畢時,內部會自動關閉並釋放文件資源。