2008年11月5日 星期三

class處理未宣告的method

class 有一個很神奇的 method,只要你在 class 中有宣告 def __getattr__(self, name),它便會把所有無法處理的優先丟給它處理。


這是一個範例
class controlMethod:
    
def otherMethod(self, name):
        
def method(*args, **kwargs):
            
print name, args, kwargs
        
return method
    
    
def __getattr__(self, name):
        
return self.otherMethod(name)
    
    
def hello(self):
        
print 'hello world'




使用起來會像這樣...
>>> c = controlMethod()
>>> c.hello()
hello world
>>> c.nono(1,2,a='die')
nono (1,2) {'a': 'die'}




在不同的應用上,也可以這樣設計
def method(*args, **kwargs):
    
print args, kwargs

class controlMethod:
    
def __getattr__(self, name):
        
return method
    
    
def hello(self):
        
print 'hello world'

沒有留言: