zoukankan      html  css  js  c++  java
  • python中一颗*args和2颗**kwargs的区别

    *args是不定长参数,有时候我们在定义函数时不确定要写几个参数时,就可以使用不定长参数。

    比如发送一个http请求,有些需要传headers,cookies,有些请求不需要,就可以使用不定长参数了。

    **kwargs是关键字参数,传递的是字典格式的参数。

    连接数据库的时候,需要传地址,数据库名,用户名,密码这些参数这个时候就可以使用关键字参数了。

    写一个配置文件,需要用的时候直接以关键字参数传递。

    import pymysql
    from tools.read_yml import read_file
    from tools.read_project_path import db_config_path
    
    
    conf = read_file(db_config_path)
    
    class DbMysql():
    
        def do_mysql(self,search_sql):
            conn = pymysql.connect(**conf)
            cursor = conn.cursor()
            cursor.execute(search_sql)
            res = cursor.fetchone()
            cursor.close()
            conn.close()
            return res
    
    if __name__ == '__main__':
        print(DbMysql().do_mysql('select * from student'))

     单独写字典传递关键字参数时,需要加上**号

    def kw_function(**kwargs):
        print(kwargs)
    
    
    kw_function(port=80,user='admin')
    
    new_dict = {"host": "localhost",
    "port": 3306,
    "user": "root",
    "password": "root",
    "database": "school"}
    
    kw_function(**new_dict)

    打印结果:

  • 相关阅读:
    随笔
    梨花落(短篇小说)
    javascript中的apply,call,bind详解
    js中this的指向问题
    你若安好,便是晴天
    gulp
    图标
    normalize.css
    git bash和toritoise客户端结合使用
    云计算基础知识
  • 原文地址:https://www.cnblogs.com/xiamaojjie/p/11920864.html
Copyright © 2011-2022 走看看