python - 如何处理需要过多参数的函数?

标签 python

我有一个看起来像这样的类:

class Product(BaseModel):
    code: str = ...
    discription_one: str = ...
    famille: FamilleProduct
    sou_famille: SouFamileProduct
    parent: ParentProduct
    sou_parent: SouParentProduct
    group: GroupProduct
    sou_group: SouGroupProduct
    reference: Optional[str] = ''
    oem: Optional[str] = ''
    other_code: Optional[str] = ''
    discription_two: Optional[str] = ''
    discription_three: Optional[str] = ''
    remarque: Optional[str] = ''
    marque: Marque
    origine: Country
    unite: UniteProduct
    code_sh: ShCode
    numbre_serie: NumbreSerie
    qr_code: QrProduct
    status: StatusProduct
    product_visible: bool = True
    product_loocked: bool = False
    product_hided: bool = False
    location: LocationProduct
    last_prix_achat: float = 0.00
    pmp_achat: float = 0.00
    prix_achat_devise: List[PrixAchat]
    prix_vente: List[PrixVente]
    tva: TvaProduct
    tax: TaxProduct
    qtt_achat: float = 0.00
    qtt_actuel: float = 0.00
    qtt_vente: float = 0.00
    qtt_min: float = 0.00
    qtt_max: float = 0.00
    qtt_arrivage: float = 0.00
    qtt_cmdfr: float = 0.00
    qtt_cmdcl: float = 0.00
    date_fab: datetime = None
    date_exp: datetime = None
    created_at: datetime = None
    updated_at: datetime = None
    images: List[ImageProduct] = None

当我尝试编写一个函数来创建这个模型时,我发现自己正在处理一个参数太多的函数:

def creat_product(self,a: str, b: str, c: None, d: None, e: None, f: None, g: None, h: None, i: str
                    j: str, k: str, l: str, m: str, n: str) -> Product:
    return Product(
        code=a,
        discription_one=b,
        famille=c,
        sou_famille=d,
        parent=e,
        sou_parent=f,
        group=g,
        sou_group=h,
        reference=i,
        oem=j,
        other_code=k,
        discription_two=l,
        discription_three=m,
        remarque=n,...# and other paramaters)

对于所有具有None值的参数,是否可以在调用creat_product时添加它们或保留它们None?还有其他方法吗?

最佳答案

您可以使用 **kwargs 来指定您的函数可以接受任意数量的参数。尽管这意味着您将能够通过提供比 Product 要求的更少的参数来调用该函数 - 但是任何问题都将直接从构造函数中报告。

def creat_product(self, **kwargs) -> Product:
   return Product(**kwargs)

你应该能够像以前一样调用它:

self.create_product(a='a', b='b', ...)

请注意,通过这种方式,您可以通过提供字典作为参数来调用该函数。例如,

my_args = {'a': 'val1', 'b': 'val2', ...}
create_product(**my_args)

作为旁注,我猜 create_product 是一个替代构造函数,因此将它更改为类方法更有意义:

@classmethod
def creat_product(cls, **kwargs):
    return cls(**kwargs)

关于python - 如何处理需要过多参数的函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66075845/

相关文章:

python - 使用 eventlet.GreenPool.spawn 时如何在主线程中引发异常

python - 为什么 np.corrcoef(x) 和 df.corr() 给出不同的结果?

Python - 元素树查找

python - 获取一个列表并返回有序对中的随机元素(必须是可变的)

python - 无法修改 django rest framework base.html 文件

Python倒计时小游戏需要指导

python - Python for 循环中的多个索引迭代

python - 所有行都期望第 0 行

python - OpenCV unproject 2D 指向具有已知深度 `Z` 的 3D

python - 在 Pandas 中读取包含列表的 csv