# Method

> 

Published: 2011-10-12
URL: https://kaochenlong.com/python-method

---

## 為什麼要寫 method?

程式碼就這樣一行一行的寫不好嗎? 當你的程式碼超過一定的行數的時候，一行一行的寫就不會是個好的寫法。通常我們會用一個抽象的名詞，來把一群連續或複合的動作給包在一起，這樣一來程式碼變得有系統了，心情也會變得比較好，重點是，會寫 method，就容易會有種變成高手的錯覺!

雖然這也許是玩笑話，但把程式碼整理到 method 裡，程式碼會變得比較好維護，而且也更容易可以重複使用。

&lt;!-- more --&gt;

## 定義

```py
def calc_method(a, b = 1):
  print a * b

def args_method(*args):
  print args

def kwargs_method(**kwargs):
  print kwargs
```

第 1 行的`calc_method`比較容易懂，這個 method 會接收 2 個參數，其中一個還是有預設值的；第 4 行的`args_method`後面的參數加了一顆`*`，表示傳進去的參數`args`會被集中成一個 Tuple；而第 7 行的`kwargs_method`則會把傳進去的參數`kwargs`集中成一個 Dictionary。

## pass!! 什麼都不做..?

前面提到 Python 的程式是靠縮排來區分 code block 的，不過如果我們寫了一個 method，但裡面目前還沒想到要寫什麼，或是在`if..else..`的判斷裡面暫時還沒想到要寫什麼內容，如果就這樣空的不理它是不行的，這時候你就需要`pass`這個什麼事都不做的東西，像這樣：

```py
def do_something():
  pass
```

或是像這樣：

```py
if age &gt;= 18:
  pass
else:
  print &quot;kid, go back to school!&quot;
```

這個`pass`的用途，就是只放個包包佔位置而已，其它什麼事都不做。也許你會覺得很不習慣，不過這個應該只有像在 Python 這種依賴縮排的程式語言才看得到的特色(?)吧。

## 呼叫/使用

```py
calc_method(4)
calc_method(4, 10)
calc_method(b = 10, a = 2)

args_method(1, 2, 3)
kwargs_method(name = &quot;eddie&quot;, age = 20)
```

Python 的 method 呼叫是透過小括號`()`，並且可以在裡面傳參數進去，不過 Python 的參數還滿自由的，不一定要照著順序傳進去，像是上面這段程式碼的第 3 行，只要知道變數名稱，用這種方式傳也是行得通的。

##回傳值
每個 method 執行結束，可以使用`return`關鍵字來指定要回傳的值，如果沒有特別指定，則回傳值是`None`(相當於在別的程式語言的`Null`或`Nil`)。所以這段程式碼的的回傳值：

```py
def calc_method(a, b = 1):
  print a * b

print calc_method(10)
```

因為`calc_method`最後並沒明確的指示要回傳什麼值，所以上面這段程式碼的執行結果，會得到在`calc_method`裡印出的結果`10`，以及用`print`把回傳值`None`給印出來。

##Lambda? 黏巴達?

```py
my_profile = lambda user_name, age : &quot;%s is %i years old&quot; % (user_name, age)
print my_profile(&quot;eddie&quot;, 30)
```

lambda 其實就是一種匿名(anonymous)的 method，它不用像一般 method 使用`def`來事先定義好。

##Method Decorator

decorator 的意思簡單的說，就是用某個 method 把你原來的 method 給包起來，也就是你在執行內層 method 之前，會先執行外層的 method。這個在 Python 或 Django 的程式碼還滿常見的，主要有兩種方式來實作：

第一種是使用 method 來做 decorator：

```py
def my_deco(func_name):
  print &quot;Hello, this is method decorator&quot;
  def wrapper():
    return func_name
  return wrapper

@my_deco
def real_method():
  print &quot;This is real method&quot;

real_method()
```

另一種是使用類別來做 decorator：

```py
class Deco(object):
  def __init__(self, func_name):
    self.func_name = func_name

  def __call__(self, *args):
    print &quot;This is a decorator class&quot;
    return self.func_name(*args)

@Deco
def real_method():
  print &quot;This is real method&quot;

real_method()
```

接下來，我們來看看在 Python 裡面的一些基本的資料型態.. 數字!

