简体   繁体   English

Python中重载参数的命名约定

[英]Naming Convention for Overloaded Parameters in Python

I was recently coding up a method in Python (numpy) that can perform its operation on either on a single element, or element-wise on an array. 我最近在用Python(numpy)编写了一个方法,该方法可以在单个元素上执行,也可以在数组上按元素执行操作。

For example: 例如:

def addOne(self, i):
    bigArray[i] += 1

Here i can either be a single index, or an array of them, which makes descriptively naming it difficult. 在这里, i可以是单个索引,也可以是它们的数组,这在描述上很难命名。

And, in the more general case, how should one name overloaded parameters that can have very different meanings? 而且,在更一般的情况下,一个名称应该如何重载可以具有不同含义的参数呢? Here's a (rather contrived) example: 这是一个(比较人为的)示例:

def doTheThing(flag, item):
    if(flag == 0):
        useOneWay(item)
    else:
        useTotallyOtherWay(item)

If item represents two totally different things here, depending on flag , how should it be named? 如果item在这里代表两个完全不同的事物,则取决于flag ,应如何命名?

Would it be better to have two named parameters with defaults? 有两个具有默认值的命名参数会更好吗? eg 例如

def doTheThing(flag, item1=None, item2=None):

Perhaps such a scenario coming up is itself an indication of bad programming practices, and the best solution is re-factoring into different methods to handle each case. 可能会出现这样的情况,这本身表明编程习惯不好,而最佳的解决方案是将其重构为不同的方法来处理每种情况。

Basically, is there a Python naming convention that gives direction here? 基本上,是否有Python命名约定在此提供指导? I couldn't find anything specifically referencing parameter overload in PEP8. 我找不到在PEP8中专门引用参数重载的任何内容。

To try and keep this on-topic and un-opinionated, please reference some reputable source in your answer (either PEP8 or some other big name in Python). 要尝试保持主题不变,请在您的答案中引用一些信誉良好的来源( PEP8或Python中的其他一些大牌子 )。 I'd be happy to hear personal opinions in the comments however. 不过,我很高兴在评论中听到个人意见。

There are several things you could do. 您可以做几件事。 The first thing is naming your variable accordingly: 首先要相应地命名变量:

def addOne(self, i_or_is):
    if not isinstance(i_or_is, list):
        i_or_is = [i_or_is]
    ...

But in this case, the better solution would probably be to take *args : 但是在这种情况下,更好的解决方案可能是采用*args

def addOne(self, *list_of_is):
    ...

which could be called like add(1) , add(1, 2, 3) or even add(*list_) (the last example unpacks an existing list into *args ). 可以像add(1)add(1, 2, 3)甚至add(*list_) (最后一个示例将现有列表解压缩为*args )。

If you have an argument that can mean different things, you can indeed split those into 2 arguments and only accept one. 如果您有一个可能表示不同含义的参数,则实际上可以将它们分为2个参数,并且只接受一个。 The standard library does this in the logging module : 标准库在日志记录模块中执行此操作:

stream - Use the specified stream to initialize the StreamHandler. stream -使用指定的流初始化StreamHandler中。 Note that this argument is incompatible with 'filename' - if both are present, a ValueError is raised. 请注意,此参数与'filename'不兼容-如果两者都存在,则会引发ValueError。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM