装饰器类的使用

class logit(object):
    def __init__(self, logfile='output.log'):
        self.logfile = logfile
    
    def __call__(self, func):
        log_string = func.__name__ + " was called"
        print(log_string)
        with open(self.logfile, 'a') as opened_file:
            opened_file.write(log_string + '\n')
        self.notify()
        
    def notify(self):
        pass
        
class email_logit(logit):
    def __init__(self, email="test@email.com", *args, **kwargs):
        self.email = email
        super().__init__(*args, **kwargs)
        
    def notify(self):
        log_string = "send an email to " + self.email
        print(log_string)
        
class message_logit(logit):
    def __init__(self, message="message log", *args, **kwargs):
        self.message = message
        super().__init__(*args, **kwargs)
        
    def notify(self):
        print(self.message)
        
@email_logit("aa@bb.com", "email.log")
def func1():
    pass

@message_logit("I'm log message", "message.log")
def func2():
    pass
    

展开阅读全文

没有更多推荐了,返回首页