2015/08/03

Python overloading in a function with default arguments

在一般的情況下,Python Function 的 overloading 必須分別寫在同名、但分開描述的 Function 內,但我真的就想要試試寫出在 Pythone 下能在同一 Function 的 overloading。

Python Function overloading with default arguments Example 案例


在這個案例中,可以利用 Python Default arguments 可使用 None 的特性,做出類似 overloading 效果的 function。
#!/usr/bin/env python
import math

def transfer(l,X = None):
  if X is None:
     print 'attribute =', l, X
     return l
  else:
   print 'attribute =', l, X
   return l,X

print transfer([1,1,0])
print transfer([1,1,0],1)


結果如下:
attribute = [1, 1, 0] None
[1, 1, 0]
attribute = [1, 1, 0] 1
([1, 1, 0], 1)


Python Function overloading with default arguments Example 案例2


我們可以試試多個 default arguments 的情況:
#!/usr/bin/env python
import math

def transfer(l,X = None,Y = None):
  if X is None and Y is None:
     print 'attribute =', l, X, Y
     return l
  elif Y is None:
     print 'attribute =', l, X, Y
     return l,X
  else:
     print 'attribute =', l, X, Y
     return l,X,Y

print transfer([1,1,0])
print transfer([1,1,0],1)
print transfer([1,1,0],1,"abc")


結果如下:
attribute = [1, 1, 0] None None
[1, 1, 0]
attribute = [1, 1, 0] 1 None
([1, 1, 0], 1)
attribute = [1, 1, 0] 1 abc
([1, 1, 0], 1, 'abc')


  1. Python Functions

沒有留言:

張貼留言