python - Default parameter value for objects -
python provides way set default value function parameters. example is:
def f(x=3): print(x)
this primitive type, lets try objects:
def f(x=list()): print(id(x)) f()
44289920
f()
44289920
same object! surprised of being used c/c++ way. done that, understand default value not build @ invoking time @ definition time.
so came solution:
def f(x=list()): if len(x) == 0: x = list() print(id(x))
solved! @ price: in opinion doesn't seem clean solution. solution rely in use of len(x) == 0
way identify default value ok function not others solution can generalized as:
def f(x=none): if x none: x = list()
this can shortened to:
def f(x=none): x = x or list() # bit shorter version
my question is, there shorter or better way solve problem? ever be?
i still prefer none approach, here new option think about: if defined type, create new instance of it.
def f(x=list): if isinstance(x, type): x = x() print(id(x))
Comments
Post a Comment