python context manager use contextlib/yield @contextmanager def send_mail_context(): '''context manager with send_mail_context() ''' try: # 1 doing work BEFORE the code goes into with block print('before yield') server = smtplib.SMTP(SMTP_SERVERS[0], 25) # 2 yield back to with/caller yield server except Exception as e: print(e) finally: # 4. doing cleanup work server.quit() print('in finally') use class __enter__, __exit__ # 2 implement contextmanager with class class SMTPCT(object): ''' 1. override __enter__ __exit__ 2. in __enter__, return value ''' def __init__(self): self.smtp_server = None def __enter__(self): # 1 doing work BEFORE the code goes into with block print('in enter') self.smtp_server = smtplib.SMTP(SMTP_SERVERS[0], 25) # 2 return back to with/caller return self.smtp_server def __exit__(self, type, value, traceback): # 4. doing cleanup work print('in exit') self.smtp_server.quit() ……
method resolution order #!/usr/bin/env python3 # -*- coding: utf-8 -*- # method resolution order # mro class A(object): def hello(self): print('class A says hello') class B(A): pass class C(A): # class variable BP_URL = 'https://xxxxx' def __init__(self): self.name = 'ok' @staticmethod def print_hello(name, age): ''' staticmethod cannot access any class or self variabel/method ''' pass @classmethod def say(cls): '''class method can access class level variable/method ''' print(cls.BP_URL) def hello(self): print('class C says hello') class D(C, B): pass if __name__ == '__main__': d = D() d.hello() # to print the mro of one class print(d.__class__.__mro__) ……