场景:python2.7没有@注解 用于实现适配器模式,不能再方法执行前后维护一些全局变量。所以用反射的思路来统一调用一个方法来执行其他的函数。
比如以下例子是为了维护一个长期使用的mysql连接,以此减少mysql的访问压力。在每次执行其他方法的时候调用
self.conn = conn_app_db.check_conn(self.conn),以此来维护连接,或者产生新连接(通过conn.ping方法判断是否连接断开)。
class upload_article(object): def __init__(self): self.conn = conn_app_db.check_conn(None) def query_one_artice(self,a): try: print self.conn sql = "select md5_url,title,author,content from article_url_log limit 1" cursor = self.conn.cursor() cursor.execute(sql) result = cursor.fetchall() if result is None: return None else: return result cursor.close() except Exception,e: print e def excute_function(self,fn_name,param): #这个用于检查连接是否可用 self.conn = conn_app_db.check_conn(self.conn) print "conn is healthy" print "start to excute function "+fn_name result = getattr(self, fn_name, None)(param) return result
总结:getattr可以通过名字返回对象的属性和函数,最后通过代入参数执行函数。