6/17/2014
6:16:00 PM 0

Named and Optional Arguments in C#, Python, JavaScript

  • C#

    C# 在使用具名引數上非常方便, function 不需做任何修改即可使用

    public double CalculateBMI(double height, double weight, bool isPrint = true)
    {
        double heightMeter = height / 100D;//double suffix
        double bmi = weight / Math.Pow(heightMeter, 2);
        //double bmi = Math.Floor(weight / Math.Pow(heightMeter, 2) * 100) / 100;
        if (isPrint) Console.WriteLine("BMI=" + bmi);
        return bmi;
    }
    

    傳入參數的方式使用類似 JSON 的表示法, 且傳入不需有順序性

    CalculateBMI(height: 170, weight: 65);
    CalculateBMI(height: 170, weight: 65, isPrint: false);
    
  • Python

    具名引數和選擇性參數,在 Python 稱做 keyword arguments & default argument values,宣告 keyword arguments 必須在函式參數的變數前面加上兩顆星號,** 可以將引數收集在一個 dictionary 物件中, 使用上要留意傳入參數宣告的順序, 下面的例子如果寫成 def calculateBMI(**keywords, isPrint=True): 是不合法的, keyword arguments 必須放在函式參數宣告的最後面

    import math
    
    def calculateBMI(isPrint=True, **keywords):
        heightMeter = keywords['height'] / 100
        bmi = keywords['weight'] / math.pow(heightMeter, 2)
        #bmi = math.floor(keywords['weight'] / math.pow(heightMeter, 2) * 100) / 100
        if isPrint:
            print('BMI=', bmi)
        return bmi
     
    calculateBMI(height = 170, weight = 65)
    calculateBMI(False, height = 170, weight = 65)
    

    Python 星號的用途不僅止於此,在某些相反情況下,譬如說你要傳遞的參數已經是一個列表但要調用的函數卻接受分開一個個的參數值,這時需要將已有的列表分拆開來,Python 有提供簡便的方式處理這樣的情形, 詳細可參考Unpacking Argument Lists, Extended Iterable Unpacking

  • JavaScript

    將多個參數集合而成一個 JavaScript 的物件當作參入傳入 function, 此種方式稱為 options hash

    function calculateBMI(options, isPrint)
    {
        var isprt = typeof(isPrint) == 'undefined' ? true : isPrint;
        var opts = options || {};
        var heightMeter = opts['height'] / 100; 
        var bmi = opts['weight'] / Math.pow(heightMeter, 2);
        //var bmi = Math.floor(opts['weight'] / Math.pow(heightMeter, 2) * 100) / 100;
        if (isprt)
            console.log('BMI=' + bmi);
        return bmi;
    }
    
    calculateBMI({height:170, weight:65})
    calculateBMI({height:170, weight:65}, false)
    

0 comments:

Post a Comment