Python中使用 词典+可变参数 简化 初始化+配置 工作

在Python中,是支持可变长参数,甚至词典参数的,具体见 《Python中函数的参数传递与可变长参数》

而使用词典参数的方式,可以让我们节省很多不必要的初始化工作。

以初始化MySQL的conn为例:

Before:

# App Config
DB_HOST = "localhost"
DB_PORT = 3306 
DB_NAME = "db"
DB_USER = "coder4"
DB_PASS = "password"

# Init conn
self.conn = MySQLdb.connect(host=DB_HOST, port=DB_PORT, user=DB_USER, passwd=DB_PASS, db=DB_NAME, use_unicode=True, charset="utf8")

After:

# DB Config
DB_CONFIG = { 
    "host" : "localhost",
    "port" : 3306,
    "user" : "coder4",
    "passwd" : "password",
    "db" : "db",
    "use_unicode" : True,
    "charset" : "utf8"
}

# Init conn
self.conn = MySQLdb.connect(**DB_CONFIG)

怎么样?简单了很多吧?

 

Leave a Reply

Your email address will not be published.