【问题标题】:Naming convention for nonmutating 'add' to a collection非变异“添加”到集合的命名约定
【发布时间】:2020-09-09 16:08:16
【问题描述】:

我有一个名为Grammar 的类,它包含一组生产规则。在对Grammar 对象进行操作之前,我通常需要为其添加一些额外的规则,这些规则应该在当前任务完成后忘记。所以,我想添加一个方法来返回一个新的Grammar 对象,其中包含所有当前对象的规则以及新的规则。

我可以调用这个方法.add,像这样:

class Grammar:

    def add(self, *rules):
        '''Returns new Grammar object, with 'rules' added.'''
        . . .

.add 传统上似乎意味着一种通过向集合添加新元素来修改集合的方法。

对于返回新集合的方法,Python 中是否存在命名约定,其中“添加”了新元素,而没有让读者期望它修改了对象?


运算符重载?

我知道.__add__ 方法是由+ 操作符调用的,并且约定确实是不修改对象——像这样:

working_grammar = grammar + [rule1, rule2, rule3]

我正在考虑避免重载运算符,以支持有意义的方法名称。但是,如果重载的运算符生成常规的、预期的、可读的代码,我想了解更多相关信息——可能是库中众所周知的先例,或者是著名的样式指南中的建议。

【问题讨论】:

  • def Get_Copy_With_Added_Rules(self, *rules) ?

标签: python collections naming-conventions immutability


【解决方案1】:

我通常用输出命名函数。另外,使用动词+宾语。一些建议:

  • add_rule(或 addRule())
  • 已添加
  • add_rule
  • 插入

For '返回一个新集合,“添加”新元素'。通常的收藏是什么?列表、元组、集合?

  • add_to_rule_list
  • add_to_rule_set

您也可以关注PEP 8 -- Style Guide for Python Code

【讨论】:

    【解决方案2】:

    concat不仅来自Python,还来自CC++;它的意思是“添加项目,然后返回对集合的引用”,如字符串连接或数组连接。

    class Grammar:
    
        def concat(self, rules):
            '''Returns new Grammar object, with 'rules' added.'''
    
    
    working_grammer = grammar.concat([rule1, rule2, rule3])
    

    pandas.concat

    您甚至可以为规则数组和其他 Grammar 对象扩展您的 concat 方法

    class Grammar:
        def concat(self, *grammarlike):
    
    grammarC = grammarA.concat(grammarB, [ruleD, ruleE])
    

    【讨论】:

      猜你喜欢
      • 2022-11-02
      • 2016-05-30
      • 1970-01-01
      • 2013-03-11
      • 1970-01-01
      • 2012-04-09
      • 1970-01-01
      • 1970-01-01
      • 2022-01-27
      相关资源
      最近更新 更多