python函数定义中的参数说明

2021-01-14 18:15

阅读:397

标签:block   python函数   stream   dha   ram   hello   val   formatter   def   

描述函数定义时 涉及到的 位置参数,默认参数,关键字参数,可变参数等的概念及用法

1 示例代码

#! /usr/bin/env python
#  -*- coding: UTF-8 -*-
import logging


def get_default_logger():
    logger = logging.getLogger()
    console_handler = logging.StreamHandler()
    formatter = logging.Formatter(‘[%(asctime)s][%(levelname)s][%(name)s][%(message)s]‘)

    console_handler.setFormatter(formatter)
    logger.addHandler(console_handler)
    logger.setLevel(logging.DEBUG)

    return logger

logger = get_default_logger()


def func(must_arg, default=‘hello‘, *args, **kwargs):
    """
    函数定义
    :param must_arg:    必要的位置参数
    :param default:     默认参数
    :param args:        任意数量的位置参数
    :param kwargs:      任意数量的关键字参数
    :return:
    """
    logger.info(‘must arg type: {}, value:{}‘.format(type(must_arg), must_arg))
    logger.info(‘default arg type: {}, value: {}‘.format(type(default), default))
    logger.info(‘mutable arg type: {}, value:{}‘.format(type(args), args))
    logger.info(‘keyword arg type: {}, value: {}‘.format(type(kwargs), kwargs))


if __name__ == ‘__main__‘:
    # 调用示例
    func(‘function demo‘, ‘hello world‘, ‘foo‘, ‘bar‘, name=‘python‘, value=‘2.7‘)

    tuple_demo = ‘foo1‘, ‘bar1‘, ‘value1‘
    func(‘function demo2‘, ‘hello‘, tuple_demo, name=‘java‘, value=‘1.8‘)

输出结果:

[2020-05-23 07:44:22,556][INFO][root][must arg type: , value:function demo]
[2020-05-23 07:44:22,556][INFO][root][default arg type: , value: hello world]
[2020-05-23 07:44:22,556][INFO][root][mutable arg type: , value:(‘foo‘, ‘bar‘)]
[2020-05-23 07:44:22,556][INFO][root][keyword arg type: , value: {‘name‘: ‘python‘, ‘value‘: ‘2.7‘}]

[2020-05-23 07:44:22,556][INFO][root][must arg type: , value:function demo2]
[2020-05-23 07:44:22,556][INFO][root][default arg type: , value: hello]
[2020-05-23 07:44:22,556][INFO][root][mutable arg type: , value:((‘foo1‘, ‘bar1‘, ‘value1‘),)]
[2020-05-23 07:44:22,556][INFO][root][keyword arg type: , value: {‘name‘: ‘java‘, ‘value‘: ‘1.8‘}]

python函数定义中的参数说明

标签:block   python函数   stream   dha   ram   hello   val   formatter   def   

原文地址:https://www.cnblogs.com/gaozhidao/p/12940919.html


评论


亲,登录后才可以留言!