python基礎教程筆記-項目1-即時標記-Day3,python-day3
昨天實現了簡單的txt轉html,今天更深入一步。
主要瞭解下帶星號的參數、getattr函數和callable函數
先看Handler類:
class Handler: def callback(self, prefix, name, *args): method = getattr(self, prefix+name, None) if callable(method): return method(*args) def start(self, name): self.callback('start_', name) def end(self, name): self.callback('end_', name) def sub(self, name): def substitution(match): result = self.callback('sub_', name, match) if result is None: match.group(0) return result return substitutiondef sub_test(self, name): print name
今天瞭解下callback函數
先看callback的參數
帶*的參數是什麼意思?
下面來看一段代碼:
def calc(*numbers):sum = 0for i in numbers:sum = sum + ireturn sumresult = calc(1,2,3)temp = calc()print resultprinta temp
執行結果為:
也就是說,帶*的參數代表一個數量可變的參數(長度可為0)。其具體講解見連結:
http://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001374738449338c8a122a7f2e047899fc162f4a7205ea3000
然後是getattr
其中官方文檔對getattr()的解釋為:
getattr(object, name[, default])
Return the value of the namedattribute of object. name must be a string. If the string is the name of one ofthe object's attributes, the result is the value of that attribute. Forexample, getattr(x, 'foobar') is equivalent to x.foobar. If the named attributedoes not exist, default is returned if provided, otherwise AttributeError israised.
也就是說,若對象中有名為name(name必須是一個字串)的屬性,則返回該屬性。如果對象中沒有該屬性,若getattr中提供了default參數,返回提供的default,否則拋出一個AttributeError錯誤。
看下面這個例子:
lass Test:def print_hello(self):print 'func print_hello work'a = Test()b = getattr(a,'print_hello',None)print bb()b = getattr(a,'NoFunc',None)print b
執行結果為:
第一次使用getattr函數時,b嘗試擷取a中的print_hello函數,從列印結果可看出擷取成功之後我們調用了b。
第二次使用getattr函數時,b嘗試擷取a中的NoFunc函數,從列印結果可看出a中並沒有名為NoneFunc的函數,因此b的值為None
接著看下callable函數
看圖
很明顯,若callable中的參數為函數名,則返回True,否則返回False。另外可以看到命令列中func()執行了一次。函數的執行發生在a = func()這一過程中
綜上,函數callback(self,prefix, name, *args)的功能為:
在使用callback函數的對象中查詢其是否擁有名為’prefix+name’的函數。若有該函數,則調用該函數,並返回該函數的執行結果。(函數名為prefix+name,參數為*args)。下面用代碼試下:
class CalTest:def callback(self,prefix,name,*args):method = getattr(self,prefix+name,None)if callable(method):return method(*args)def printSum(self,*arg):sum = 0for i in arg:sum = sum + ireturn suma = CalTest();b = a.callback('print','Sum',1,2,3)print bb = a.callback('print','Sum')print b執行結果為: