1. 遞歸html
2. 反射python
3. 反射重點--函數路徑git
4. 加密模塊hashlib正則表達式
5. 模塊之正則(re)算法
若是函數包含了對其自身的調用,該函數就是遞歸的。express
實例:app
def func(n): if n == 1: return 1 return n*func(n-1) n = func(3) print(n)
代碼解析:ide
定義了一個func函數,傳入數字參數,當數字參數爲1時,返回1;else:執行參數*參數遞減1,這種函數調用函數自己的行爲,就是遞歸;函數
插入一些關於遞歸的解釋,如下是從網上搜到的內容:
(1)遞歸就是在過程或函數裏調用自身;
(2)在使用遞歸策略時,必須有一個明確的遞歸結束條件,稱爲遞歸出口。ui
遞歸算法通常用於解決三類問題:
(1)數據的定義是按遞歸定義的。(好比Fibonacci函數)
(2)問題解法按遞歸算法實現。(回溯)
(3)數據的結構形式是按遞歸定義的。(好比樹的遍歷,圖的搜索)
遞歸的缺點:遞歸算法解題的運行效率較低。在遞歸調用的過程中系統爲每一層的返回點、局部量等開闢了棧來存儲。遞歸次數過多容易形成棧溢出等。
python中的反射功能是由如下四個內置函數提供:hasattr、getattr、setattr、delattr,這四個函數分別用於對對象內部執行:檢查是否含有某成員、獲取成員、設置成員、刪除成員。
class Foo(object): def __init__(self): self.name = 'liuhailong' def func(self): return 'func' obj = Foo() # #### 檢查是否含有成員 #### hasattr(obj, 'name') hasattr(obj, 'func') # #### 獲取成員 #### getattr(obj, 'name') getattr(obj, 'func') # #### 設置成員 #### setattr(obj, 'age', 18) setattr(obj, 'show', lambda num: num + 1) # #### 刪除成員 #### delattr(obj, 'name') delattr(obj, 'func')
詳細解析:
當咱們要訪問一個對象的成員時,應該是這樣操做:
class Foo(object): def __init__(self): self.name = 'alex' def func(self): return 'func' obj = Foo() # 訪問字段 obj.name # 執行方法 obj.func()
class Foo(object): def __init__(self): self.name = 'alex' # 不容許使用 obj.name obj = Foo()
答:有兩種方式,以下:
方法一
class Foo(object): def __init__(self): self.name = 'alex' def func(self): return 'func' # 不容許使用 obj.name obj = Foo() print(obj.__dict__['name'])
方法二
class Foo(object): def __init__(self): self.name = 'alex' def func(self): return 'func' # 不容許使用 obj.name obj = Foo() print(getattr(obj, 'name'))
d、比較三種訪問方式
答:第一種和其餘種比,...
第二種和第三種比,...
#!/usr/bin/env python #coding:utf-8 from wsgiref.simple_server import make_server class Handler(object): def index(self): return 'index' def news(self): return 'news' def RunServer(environ, start_response): start_response('200 OK', [('Content-Type', 'text/html')]) url = environ['PATH_INFO'] temp = url.split('/')[1] obj = Handler() is_exist = hasattr(obj, temp) if is_exist: func = getattr(obj, temp) ret = func() return ret else: return '404 not found' if __name__ == '__main__': httpd = make_server('', 8001, RunServer) print ("Serving HTTP on port 8000...") httpd.serve_forever()
一般咱們在寫程序時,爲了程序可讀性更好,會將程序內容按不一樣功能,寫到多個目錄裏,可是程序間,有時須要調用不一樣目錄下的函數,來實現相應的功能,增長代碼的重用性等,這時就涉及到路徑了。這部分是基礎,也是關鍵!!!
實例(一)如圖:
代碼:
import sys import os project_path =os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.append(project_path) from commons import authentication if __name__ == '__main__': hasattr(authentication,"login") login = getattr(authentication,"login") login() authentication.login() main.py ___________________________________ def login(): print('登陸頁面') def logout(): print('退出頁面') def home(): print('進入家目錄') authencatition.py
實例(二)
代碼解析:
__file__ 獲取文件的絕對路徑,若是單一執行此內置函數,獲取的是文件名;
os.path.abspath(__file__) 是獲取文件的絕對路徑,不是文件名;
__import__ 這是奇蹟的根源,內置函數能夠將字符串類型解析成模塊目錄名;
m,f = inp.split('/') 定義兩個參數,傳參時必須是兩個參數,而且以‘/’做爲分隔符;
總結: 反射就是利用字符串的形式去對象(模塊)中操做(尋找/檢查/刪除/設置)成員。
反射方法用於自定義模塊間調用函數方法,很是方便,是最佳之選!!!
源碼:hashlib module - A common interface to many hash functions.多種hash函數的通用接口
hashlib用來替換md5和sha模塊,並使他們的API一致。它由OpenSSL支持,支持以下算法:md5,sha1, sha224, sha256, sha384, sha512。
Hash objects have these methods:
- update(arg): Update the hash object with the bytes in arg. Repeated calls
are equivalent to a single call with the concatenation of all
the arguments.
- digest(): Return the digest of the bytes passed to the update() method
so far.
- hexdigest(): Like digest() except the digest is returned as a unicode
object of double length, containing only hexadecimal digits.
- copy(): Return a copy (clone) of the hash object. This can be used to
efficiently compute the digests of strings that share a common
initial substring.
For example, to obtain the digest of the string 'Nobody inspects the spammish repetition': >>> import hashlib >>> m = hashlib.md5() >>> m.update(b"Nobody inspects") >>> m.update(b" the spammish repetition") >>> m.digest() b'\\xbbd\\x9c\\x83\\xdd\\x1e\\xa5\\xc9\\xd9\\xde\\xc9\\xa1\\x8d\\xf0\\xff\\xe9'
Python3和Python2有區別
import hashlib obj = hashlib.md5(bytes("abcd",encoding='utf-8')) obj.update(bytes('123',encoding="utf-8")) result = obj.hexdigest() print(result)
執行加密要使用bytes;
這個模塊提供了與 Perl 類似l的正則表達式匹配操做。Unicode字符串也一樣適用。
正則表達式使用反斜槓" \ "來表明特殊形式或用做轉義字符,這裏跟Python的語法衝突,所以,Python用" \\\\ "表示正則表達式中的" \ ",由於正則表達式中若是要匹配" \ ",須要用\來轉義,變成" \\ ",而Python語法中又須要對字符串中每個\進行轉義,因此就變成了" \\\\ "。
上面的寫法是否是以爲很麻煩,爲了使正則表達式具備更好的可讀性,Python特別設計了原始字符串(raw string),須要提醒你的是,在寫文件路徑的時候就不要使用raw string了,這裏存在陷阱。raw string就是用'r'做爲字符串的前綴,如 r"\n":表示兩個字符"\"和"n",而不是換行符了。Python中寫正則表達式時推薦使用這種形式。
絕大多數正則表達式操做與 模塊級函數或RegexObject方法 同樣都能達到一樣的目的。並且不須要你一開始就編譯正則表達式對象,可是不能使用一些實用的微調參數。
Support for regular expressions (RE). This module provides regular expression matching operations similar to those found in Perl. It supports both 8-bit and Unicode strings; both the pattern and the strings being processed can contain null bytes and characters outside the US ASCII range. Regular expressions can contain both special and ordinary characters. Most ordinary characters, like "A", "a", or "0", are the simplest regular expressions; they simply match themselves. You can concatenate ordinary characters, so last matches the string 'last'. The special characters are: "." Matches any character except a newline. "^" Matches the start of the string. "$" Matches the end of the string or just before the newline at the end of the string. "*" Matches 0 or more (greedy) repetitions of the preceding RE. Greedy means that it will match as many repetitions as possible. "+" Matches 1 or more (greedy) repetitions of the preceding RE. "?" Matches 0 or 1 (greedy) of the preceding RE. *?,+?,?? Non-greedy versions of the previous three special characters. {m,n} Matches from m to n repetitions of the preceding RE. {m,n}? Non-greedy version of the above. "\\" Either escapes special characters or signals a special sequence. [] Indicates a set of characters. A "^" as the first character indicates a complementing set. "|" A|B, creates an RE that will match either A or B. (...) Matches the RE inside the parentheses. The contents can be retrieved or matched later in the string. (?aiLmsux) Set the A, I, L, M, S, U, or X flag for the RE (see below). (?:...) Non-grouping version of regular parentheses. (?P<name>...) The substring matched by the group is accessible by name. (?P=name) Matches the text matched earlier by the group named name. (?#...) A comment; ignored. (?=...) Matches if ... matches next, but doesn't consume the string. (?!...) Matches if ... doesn't match next. (?<=...) Matches if preceded by ... (must be fixed length). (?<!...) Matches if not preceded by ... (must be fixed length). (?(id/name)yes|no) Matches yes pattern if the group with id/name matched, the (optional) no pattern otherwise. The special sequences consist of "\\" and a character from the list below. If the ordinary character is not on the list, then the resulting RE will match the second character. \number Matches the contents of the group of the same number. \A Matches only at the start of the string. \Z Matches only at the end of the string. \b Matches the empty string, but only at the start or end of a word. \B Matches the empty string, but not at the start or end of a word. \d Matches any decimal digit; equivalent to the set [0-9] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode digits. \D Matches any non-digit character; equivalent to [^\d]. \s Matches any whitespace character; equivalent to [ \t\n\r\f\v] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the whole range of Unicode whitespace characters. \S Matches any non-whitespace character; equivalent to [^\s]. \w Matches any alphanumeric character; equivalent to [a-zA-Z0-9_] in bytes patterns or string patterns with the ASCII flag. In string patterns without the ASCII flag, it will match the range of Unicode alphanumeric characters (letters plus digits plus underscore). With LOCALE, it will match the set [0-9_] plus characters defined as letters for the current locale. \W Matches the complement of \w. \\ Matches a literal backslash. This module exports the following functions: match Match a regular expression pattern to the beginning of a string. fullmatch Match a regular expression pattern to all of a string. search Search a string for the presence of a pattern. sub Substitute occurrences of a pattern found in a string. subn Same as sub, but also return the number of substitutions made. split Split a string by the occurrences of a pattern. findall Find all occurrences of a pattern in a string. finditer Return an iterator yielding a match object for each match. compile Compile a pattern into a RegexObject. purge Clear the regular expression cache. escape Backslash all non-alphanumerics in a string. Some of the functions in this module takes flags as optional parameters: A ASCII For string patterns, make \w, \W, \b, \B, \d, \D match the corresponding ASCII character categories (rather than the whole Unicode categories, which is the default). For bytes patterns, this flag is the only available behaviour and needn't be specified. I IGNORECASE Perform case-insensitive matching. L LOCALE Make \w, \W, \b, \B, dependent on the current locale. M MULTILINE "^" matches the beginning of lines (after a newline) as well as the string. "$" matches the end of lines (before a newline) as well as the end of the string. S DOTALL "." matches any character at all, including the newline. X VERBOSE Ignore whitespace and comments for nicer looking RE's. U UNICODE For compatibility only. Ignored for string patterns (it is the default), and forbidden for bytes patterns. This module also defines an exception 'error'.
實例(一):
atch:re.match(pattern, string, flags=0) flags 編譯標誌位,用於修改正則表達式的匹配方式,如:是否區分大小寫, 多行匹配等等。 re.match('com', 'comwww.runcomoob').group() re.match('com', 'Comwww.runComoob',re.I).group()
實例(二)
search:re.search(pattern, string, flags=0) re.search('\dcom', 'www.4comrunoob.5com').group() 注意: re.match('com', 'comwww.runcomoob') re.search('\dcom', 'www.4comrunoob.5com') 一旦匹配成功,就是一個match object 對象,而match object 對象擁有如下方法: group() 返回被 RE 匹配的字符串 start() 返回匹配開始的位置 end() 返回匹配結束的位置 span() 返回一個元組包含匹配 (開始,結束) 的位置 group() 返回re總體匹配的字符串,能夠一次輸入多個組號,對應組號匹配的字符串。import re a = "123abc456" re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(0) #123abc456,返回總體 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(1) #123 re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(2) #abc re.search("([0-9]*)([a-z]*)([0-9]*)",a).group(3) #456 group(1) 列出第一個括號匹配部分,group(2) 列出第二個括號匹配部分,group(3) 列出第三個括號匹配部分。
實例(三)
findall: re.findall 以列表形式返回全部匹配的字符串 re.findall能夠獲取字符串中全部匹配的字符串。如: p = re.compile(r'\d+') print p.findall('one1two2three3four4') re.findall(r'\w*oo\w*', text);獲取字符串中,包含'oo'的全部單詞。 import re text = "JGood is a handsome boy,he is handsome and cool,clever,and so on ...." print(re.findall(r'\w*oo\w*',text)) #結果:['JGood', 'cool'] #print re.findall(r'(\w)*oo(\w)*',text) # ()表示子表達式 結果:[('G', 'd'), ('c', 'l')] finditer(): >>> p = re.compile(r'\d+') >>> iterator = p.finditer('12 drumm44ers drumming, 11 ... 10 ...') >>> for match in iterator: match.group() , match.span()
實例(四)
sub subn: re.sub(pattern, repl, string, max=0) re.sub("g.t","have",'I get A, I got B ,I gut C')
re.I 使匹配對大小寫不敏感
re.L 作本地化識別(locale-aware)匹配
re.M 多行匹配,影響 ^ 和 $
re.S 使 . 匹配包括換行在內的全部字符
>>> re.findall(".","abc\nde")
>>> re.findall(".","abc\nde",re.S)
re.U 根據Unicode字符集解析字符。這個標誌影響 \w, \W, \b, \B.
re.X 該標誌經過給予你更靈活的格式以便你將正則表達式寫得更易於理解。
re.S:.將會匹配換行符,默認.逗號不會匹配換行符>>> re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b") []>>> re.findall(r"a(\d+)b.+a(\d+)b","a23b\na34b",re.S) [('23','34')]>>>re.M:^$標誌將會匹配每一行,默認^只會匹配符合正則的第一行;默認$只會匹配符合正則的末行