• [Python] Pitfalls: About Default Parameter Values in Functions


    Today an interesting bug (pitfall) is found when I was trying debug someone's code. There is a function which tries to check if an object exists or not. It has several parameters and some of them have default value. When using this function, the programmer intended to give some values to some certain parameters but keep the rest for default values. However I astonishedly found that the passed parameters are not those as we intended to pass. For example, we have a function defined like this:

    def printDefaultParas(para_1, para_2 = False, para_3 = False):
        print("para_1=%s, para_2=%s, para_3=%s"%(para_1, para_2, para_3))

    Then, we have some other functions called it, for example one of them could be:

    def pitfallHappens():
        para_1 = "This is Para 1"
        para_3 = True
        printDefaultParas(para_1, para_3)

    What we expected (or we intended) to have is, the function prints out:

    para_1=This is Para 1, para_2=False, para_3=True

    But what we actually got will be:

    para_1=This is Para 1, para_2=True, para_3=False

    Why?

    In fact, it is because, in the function pitfallHappens(), when we call function printDefaultParas(), these para_1, and para_3 we put in the parameter list, do not stand for the parameters at all. They are just variables happened to be the same name as the parameter names! As a result, Python will put this values accordingly in the sequence of the parameter list, and leave the rest as their default values (if possible). In this case, it gives the variable para_1's value ("This is Para 1") to parameter para_1, and variable para_3's value (True) to parameter para_2, and leave parameter para_3 as its default value (False).

    Now we are clear, and function pitfallHappens() could be corrected as:

    def pitfallCorrected():
        para_1 = "This is Para 1"
        para_3 = True
        printDefaultParas(para_1 = para_1, para_3 = para_3)

    Then pitfallCorrected() will get expected result.

  • 相关阅读:
    子线程循环10次,接着主线程循环100,接着又回到子线程循环10次.....如此循环50次
    java面向对象中的String类中12种常用的方法
    网络编程TCP协议-聊天室
    网络编程(UDP协议-聊天程序)
    Swing布局管理器
    java排序方法中的选择排序方法
    java排序方法中的插入排序方法
    java数组中的三种排序方法中的冒泡排序方法
    css3模仿雨滴(附源码)
    html5+css3实现3D图片(附源码)
  • 原文地址:https://www.cnblogs.com/cheese-bacon/p/3446443.html
Copyright © 2020-2023  润新知