- # Python 編程語言中有四種集合數據類型:
- # 集合數據類型 序(ordered) 重複成員(duplicate)
- # 列表 list 有序,且可變 允許重複
- # 元組 tuple 有序,不可變 允許重複
- # 集 set 無序,且無索引 沒有重複
- # 字典 dictionary 有序,且可變 沒有重複
- # 以下是範例:
- def demo_list(obj = []): # 可變默認參數 mutable default argument
- print(obj)
- obj.append(1)
- def demo_tuple(obj = ()):
- print(obj)
- obj = (1) # 重新賦值
- def demo_set(obj = set()): # 可變默認參數 mutable default argument
- print(obj)
- obj.add(1)
- def demo_dict(obj = {}): # 可變默認參數 mutable default argument
- print(obj)
- obj['one'] = 1
- demo_list() # []
- demo_list() # [1]
- demo_tuple() # ()
- demo_tuple() # ()
- demo_set() # set()
- demo_set() # {1}
- demo_dict() # {}
- demo_dict() # {'one': 1}
- # 這裡發現,只有元組 tuple 沒有被影響
- # 其它卻因為第一次調用時候已經改變默認參數值了
- # ----------------------------------------------------------------------------------------------------
- # 解決方法:
- def demo_list(obj = None): # 默認參數為'無'
- obj = []
- print(obj)
- obj.append(1)
- demo_list() # []
- demo_list() # []
- # ----------------------------------------------------------------------------------------------------
- # 來自於 The Hitchhiker's Guide to Python
- # by Kenneth Reitz, Tanya Schlusser
- # Mutable Default Arguments
- # What You Might Have Expected to Happen?
- # Python’s default arguments are evaluated once when the function is defined,
- # not each time the function is called (like it is in say, Ruby).
- # This means that if you use a mutable default argument and mutate it,
- # you will and have mutated that object for all future calls to the function as well.
复制代码 |