zoukankan      html  css  js  c++  java
  • C/C++ Python的函数默认参数

    发现C/C++  Python的函数可以使用默认参数,来减少传参时候的参数个数。

    但是:这样的默认参数最好是不变对象!

    #include <stdio.h>
    #include <string.h>
    
    void func_1(int id, char s[], char city[] = "Bejing")
    {
        printf("%d, %s, %s",id, s, city);
    }
    
    int main()
    {
        func_1(1, "李金旭");
    
        return 0;
    }
    def add_end(L = []):
        L.append('End')
        return L
    print(add_end())
    print(add_end())
    '''['End']['End', 'End']

    Python函数在定义的时候,默认参数L的值就被计算出来了,即[],因为默认参数L也是一个变量,它指向对象[],每次调用该函数,如果改变了L的内容,则下次调用时,默认参数的内容就变了,不再是函数定义时的[]了。

    所以,定义默认参数要牢记一点:默认参数必须指向不变对象!

    '''
    def add_end(L = None):
        if L is None:
            L = []
        L.append('End')
        return L
    print(add_end())
    print(add_end())
    '''['End']['End']'''
  • 相关阅读:
    文件操作
    set集合,深浅拷贝
    is 和 == 区别 id()函数
    字典
    列表
    基本数据类型
    第十二章 if测试和语法规则
    第十一章 赋值、表达式和打印
    第十章 python语句简介
    第九章元组、文件及其他
  • 原文地址:https://www.cnblogs.com/luntai/p/5573331.html
Copyright © 2011-2022 走看看