2016-11-14 26 views
0

我需要一個裝飾器,它需要一個參數,並且該方法應該被允許運行(基於一些簡單的邏輯)或引發異常。但我不知道我該如何寫這個裝飾器。讓我們的方法運行或引發異常的Python裝飾器

class One(obj): 
    trend = "trend" 
    @myDecorator(self.trend) 
    def click_button(self): 
     clickable_element = self.driver.find_element_by_id(self.trend) 
     clickable_element.click() 
     return self 


class Two(obj): 
    map = "map" 

    @myDecorator(self.map) 
    def click_button(self): 
     clickable_element = self.driver.find_element_by_id(self.map) 
     clickable_element.click() 
     return self 

的邏輯應該是這樣的:

def my Decorator(arg): 
    if arg: 
     "run the method" 
    else: 
     raise "Exception" 

回答

1
def parametrised_decorator(parameter): 
    def parametrised(function): 
     @functools.wraps(function) 
     def inner(*args, **kwargs): 
      if parameter: 
       return function(*args, **kwargs) 
      else: 
       raise Exception() 

     return inner 

    return parametrised 
0
def my_Decorator(arg=None): 
    def decorator(func): 
     def wrapper(*args, **kwargs): 
      if arg: 
       return func(*args, **kwargs) 

      else: 
       raise Exception() 

     return wrapper 

    return decorator 
0
from functools import wraps 


def my_decorator(f): 
    @wraps(f) 
    def wrapper(*args, **kwargs): 
     if kwargs.pop('runit', None): 
      return f(*args, **kwargs) 
     else: 
      raise Exception() 
    return wrapper 


@my_decorator 
def example(): 
    print('example') 


if __name__ == '__main__': 
    # runs function 
    example(runit=True) 
    # runs exception 
    example()