python中一个参数的文档约定是什么?只有在使用另一个参数时,该参数才是可选的



假设我有一个函数create_person,它创建了一个person对象,现在假设我想给用户一个用create_person('Tomer', 19, ...)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)
...

如果您想使用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)

由于缺少太多信息,很难判断什么是解决确切问题的正确方法。

相关内容

最新更新