iT邦幫忙

2018 iT 邦幫忙鐵人賽
DAY 11
0
自我挑戰組

if len(learning.python) == 30:系列 第 18

Day18-Function-Argument語法糖

關於function的arguments,也就是使用function時帶入的東西,有三種語法糖可以使用。

  • Default Argument Values
  • Keyword Arguments
  • Arbitrary Argument Lists

parameters和arguments有何不同?
差別在於各自代表在定義階段和呼叫階段所使用的東西

Default Argument Values

事先定義預設值,減少呼叫時帶入的參數數量。

要注意兩件事

  1. 預設值在function定義階段的時間點決定
  2. 預設值只會被決定一次,必須特別注意傳入的參數是否為mutable
# The default values are evaluated at the point of function definition in the defining scope
default_score = 100
def re_score(s=default_score):
    print( "score before: {}".format(s) )
    s = s * 10
    print( "score after: {}".format(s) )

default_score = 120
re_score()

# score before: 100
# score after: 1000


# The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes.
# default to be shared between subsequent calls
def add_score(s, class_sroces=[]):
    class_sroces.append(s)
    return class_sroces

print(add_score(60))
print(add_score(84))
print(add_score(99))

# [60]
# [60, 84]
# [60, 84, 99]


# don’t want the default to be shared between subsequent calls
def add_score_independent(s, class_sroces=None):
    if class_sroces is None:
        class_sroces = []
    class_sroces.append(s)
    return class_sroces

print(add_score_independent(60))
print(add_score_independent(84))
print(add_score_independent(99))

# [60]
# [84]
# [99]

Keyword Arguments

有兩種augements

  • keyword argument
    • an argument preceded by an identifier (e.g. name=) in a function call
    • passed as a value in a dictionary preceded by **
  • positional argument
    • an argument that is not a keyword argument.
    • passed as elements of an iterable preceded by *

使用時有先後順序的限制 : formal parameters => positional argument(*name) => keyword argument(**name)

def re_score(cal_base ,default_score=100, who='ming', clazz='A'):
    output = '{who} score before in class {clazz}: {score}'
    print( output.format(who=who, clazz=clazz, score=default_score) )
    score = default_score * cal_base
    print( output.format(who=who, clazz=clazz, score=score) )

try:
    re_score()
except TypeError as e:
    print( "Type Error:: {0}".format(e) )
# Type Error:: re_score() missing 1 required positional argument: 'cal_base'


re_score(20)

# ming score before in class A: 100
# ming score before in class A: 2000


re_score(cal_base=20)

# ming score before in class A: 100
# ming score before in class A: 2000


# re_score(cal_base=20, 20)
# SyntaxError: positional argument follows keyword argument

re_score(20, 20)

# ming score before in class A: 20
# ming score before in class A: 400


re_score(20, 30, 'john')

# john score before in class A: 30
# john score before in class A: 600


re_score(20, clazz="B")

# ming score before in class B: 100
# ming score before in class B: 2000


try:
    re_score(20, name='tom')
except TypeError as e:
    print( "Type Error:: {0}".format(e) )

# Type Error:: re_score() got an unexpected keyword argument 'name'


# passed as a value in a dictionary preceded by **
info = {'default_score':80, 'who':'tom', 'clazz':'B'}
re_score(20, **info)

# tom score before in class B: 80
# tom score before in class B: 1600

Arbitrary Argument Lists

使用任意數量的Argument

def concat(prefix, *chunk, sep="/"):
    return prefix + sep.join(chunk)


result = concat('https://', 'ithelp.ithome.com.tw', 'articles', '10192583')
print( "concat result:{}".format(result) )

# concat result:https://ithelp.ithome.com.tw/articles/10192583


url_domain_chunk = ('docs', 'python', 'org')
url_path_chunk = ('3', 'tutorial', 'controlflow.html')

domain = concat('https://', *url_domain_chunk, sep='.')
url = concat(domain, *url_path_chunk)
url_with_tag = concat(url+"#", 'more-on-defining-functions', sep='')
print( "concat domain:{}".format(domain) )
print( "concat url:{}".format(url) )
print( "concat url_with_tag:{}".format(url_with_tag) )

# concat domain:https://docs.python.org
# concat url:https://docs.python.org3/tutorial/controlflow.html
# concat url_with_tag:https://docs.python.org3/tutorial/controlflow.html#more-on-defining-functions

參考


上一篇
Day17-Function-概觀
下一篇
Day19-Function-lambda和decorator語法糖
系列文
if len(learning.python) == 30:31
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言