python中如何使用导入的方法初始化默认值?
How to use a imported method for initialization of default value in python?
我有一个 Helper.py 看起来像这样:
def toDayDate():
return Now()
def getAge(dob,today=toDayDate()):
doMagic()
那我就用在这里:
from helper import getAge
input=getDOBfromUSER()
getAge(input)
问题出在 python 解释导入时
toDayDate() 无论如何都是 运行!!!
我做错了什么?
以上设置是为了将参数设置为默认动态
参数的默认值在 Python 中定义时计算。为了有效地使默认值在 运行 时计算,一种常见的方法是将默认值设置为 None
,然后使用条件将其设置为函数内动态计算的值:
def getAge(dob, today=None):
if today is None:
today = toDayDate()
doMagic()
您可能需要阅读以下资源:
- https://docs.python-guide.org/writing/gotchas/
- python function default parameter is evaluated only once?
- "Least Astonishment" and the Mutable Default Argument
当你这样声明时:
def getAge(dob,today=toDayDate()):
引用这些参考资料:
Python’s default arguments are evaluated once when the function is defined, not each time the function is called
让我们证明一下:
>>> from datetime import datetime
>>>
>>>
>>> datetime.now() # Display the time before we define the function
datetime.datetime(2021, 9, 28, 17, 54, 16, 761492)
>>>
>>> def func(var=datetime.now()): # Set the time to now
... print(var)
...
>>> func()
2021-09-28 17:54:16.762774
>>> func()
2021-09-28 17:54:16.762774
>>> func()
2021-09-28 17:54:16.762774
如您所见,即使我们在几分钟、几小时或几天后调用 func()
,它的值将固定为我们定义它的时间,并且不会在每次更改时实际更改称呼。这也证明,一旦您定义了一个函数(或导入了一个包含该函数的文件),它的定义就已经被评估了,其中包括它的默认参数。在设置默认参数之前,它不会等待您先调用该函数。
您需要做的是:
def getAge(dob,today=None):
if today is None:
today = toDayDate()
doMagic()
或者您可以利用布尔短路:
def getAge(dob,today=None):
today = today or toDayDate()
doMagic()
我有一个 Helper.py 看起来像这样:
def toDayDate():
return Now()
def getAge(dob,today=toDayDate()):
doMagic()
那我就用在这里:
from helper import getAge
input=getDOBfromUSER()
getAge(input)
问题出在 python 解释导入时 toDayDate() 无论如何都是 运行!!!
我做错了什么?
以上设置是为了将参数设置为默认动态
参数的默认值在 Python 中定义时计算。为了有效地使默认值在 运行 时计算,一种常见的方法是将默认值设置为 None
,然后使用条件将其设置为函数内动态计算的值:
def getAge(dob, today=None):
if today is None:
today = toDayDate()
doMagic()
您可能需要阅读以下资源:
- https://docs.python-guide.org/writing/gotchas/
- python function default parameter is evaluated only once?
- "Least Astonishment" and the Mutable Default Argument
当你这样声明时:
def getAge(dob,today=toDayDate()):
引用这些参考资料:
Python’s default arguments are evaluated once when the function is defined, not each time the function is called
让我们证明一下:
>>> from datetime import datetime
>>>
>>>
>>> datetime.now() # Display the time before we define the function
datetime.datetime(2021, 9, 28, 17, 54, 16, 761492)
>>>
>>> def func(var=datetime.now()): # Set the time to now
... print(var)
...
>>> func()
2021-09-28 17:54:16.762774
>>> func()
2021-09-28 17:54:16.762774
>>> func()
2021-09-28 17:54:16.762774
如您所见,即使我们在几分钟、几小时或几天后调用 func()
,它的值将固定为我们定义它的时间,并且不会在每次更改时实际更改称呼。这也证明,一旦您定义了一个函数(或导入了一个包含该函数的文件),它的定义就已经被评估了,其中包括它的默认参数。在设置默认参数之前,它不会等待您先调用该函数。
您需要做的是:
def getAge(dob,today=None):
if today is None:
today = toDayDate()
doMagic()
或者您可以利用布尔短路:
def getAge(dob,today=None):
today = today or toDayDate()
doMagic()