第20条-用None和文档字符串来描述具有动态默认值的参数
关键:
1 参数的默认值
特点: 包含代码的模块一旦加载进来,参数的默认值就不变了
2 动态设置默认值
把默认值设置为None,如果发现参数的值为None,就设置为默认值
先看一个示例
def log1(content, when=datetime.utcnow()): print("content: {content}, when: {when}".format(content=content, when=when)) def log2(content, when=None): """ :param content: :param when: :return: """ when = datetime.utcnow() if when is None else when print("content: {}, when: {}".format(content, when)) def process(): log1('test1') time.sleep(1) log1('test2') print('=====') log2('test1') time.sleep(1) log2('test2') if __name__ == "__main__": process() #输出 content: test1, when: 2019-12-08 14:47:52.839435 content: test2, when: 2019-12-08 14:47:52.839435 ===== content: test1, when: 2019-12-08 14:47:53.841040 content: test2, when: 2019-12-08 14:47:54.842983
接着再看下一个示例:
import json # global var default of dict type which is mutable def decode_data(data, default={}): try: return json.loads(data) except Exception as e: # print(e) return default foo = decode_data('name') foo['name'] = 's' bar = decode_data('age') bar['age'] = 18 print('foo:', foo) print('bar:', bar) print('foo is bar:', foo is bar) print(id(foo) == id(bar)) # foo: {'name': 's', 'age': 18} # bar: {'name': 's', 'age': 18} # foo is bar: True # True def decode_data_test(data): print('\n====decode_data_test') def decode_data(data, default={}): try: return json.loads(data) except Exception as e: # print(e) return default return decode_data(data) foo = decode_data_test('name') foo['name'] = 's' bar = decode_data_test('age') bar['age'] = 18 print('foo:', foo) print('bar:', bar) print('foo is bar:', foo is bar) print(id(foo) == id(bar)) # ====decode_data_test # # ====decode_data_test # foo: {'name': 's'} # bar: {'age': 18} # foo is bar: False # False