亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

僅當使用另一個參數時可選的參數在 python 中的文檔約定是什么

僅當使用另一個參數時可選的參數在 python 中的文檔約定是什么

海綿寶寶撒 2023-06-06 15:27:46
假設我有一個create_person創建 person 對象的函數,現在假設我想為用戶提供使用 withcreate_person('Tomer', 19, ...)或 with調用它的選項create_person(base_person=tomer_person, ...),我應該如何正確記錄此行為?這是定義函數的正確方法嗎?例子:def create_person(name=None, age=None, base_person=None):    if not name and not age and base_person:        person = base_person    elif not base_person:        person = Person(name, age)    ...
查看完整描述

1 回答

?
繁花不似錦

TA貢獻1851條經驗 獲得超4個贊

如果你想使用numpydoc樣式,一種可能的方法是:


def create_person(name=None, age=None, base_person=None):

    r"""A function to create a person.


    Using this function, a person can be created using

    either a combination of `name` and `age` or providing a `base_person`.


    Parameters

    ----------

    name : int [optional, default=None]

        The name of the person to be created. Leave this as None to create a person

        using the `base_person` keyword.

    age : int [optional, default=None]

        The age of the person to be created. Leave this as None to create a person

        using the `base_person` keyword. 

    base_person : instance of Person class [optional, default=None]

        If `age` and `name` are None, this keyword can be used to create a person

        from an instance of the `Person` class."""

就個人而言,我會創建兩種不同的函數,一種是根據姓名和年齡創建人,另一種是使用對象base_person。在內部,他們可以使用正確的調用者簽名調用您提供的函數。例如:


def create_person_explicit(name, age):

    return(create_person(name=name, age=age)


def create_person_from_object(base_person):

    return(create_person(base_person=base_person)

由于缺少太多信息,很難說出什么是針對您的具體問題的正確解決方案。


查看完整回答
反對 回復 2023-06-06
  • 1 回答
  • 0 關注
  • 143 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號