gpt4 book ai didi

python明确不传递可选参数

转载 作者:太空宇宙 更新时间:2023-11-03 13:03:11 24 4
gpt4 key购买 nike

设想以下场景:

class A:
def __init__(self, arg1=3, arg2=5):
pass

def createA(arg1=None, arg2=None):
if arg1 is None:
if arg2 is None:
a = A()
else:
a = A(arg2=arg2)
else:
if arg2 is None:
a = A(arg1=arg1)
else:
a = A(arg1=arg1, arg2=arg2)
return a

实现此行为的最佳方式是什么,请牢记以下几点:

  • 我不能/不想更改类 A
  • 我不想显式地将 A 的构造函数参数的默认值添加到 createA 函数中?

例如,是否有任何值表示未传递可选参数?像这样的东西:

if arg1 is None:
newArg1 = NotPassed
else:
newArg1 = arg1

if arg2 is None:
newArg2 = NotPassed
else:
newArg2 = arg2
A(arg1=newArg1, arg2=newArg2)

最佳答案

def create_A(arg1=None, arg2=None):
kwargs = {}
if arg1 is not None: kwargs['arg1'] = arg1
if arg1 is not None: kwargs['arg2'] = arg2
return A(**kwargs)

甚至可能

def create_A(**kwargs):
return A(**kwargs)

关于python明确不传递可选参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12960012/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com