在python

是否有约定何时以及如何在python中存储len()sum()的值?举个例子,如果你有一个班级

class MyClass:

    def __init__(self,single_number = 4,multiple_numbers = [1,2,3]):
        self.single= single_number 
        self.multiple = multiple_numbers

    def info(self):
        print(f"The length of multiple is {len(self.multiple)}")
        print(f"The length of multiple is {len(self.multiple)*4}")
        print(f"The length of multiple is longer than {len(self.multiple)-1}")

if __name__ == "__main__":
    test=MyClass()
    test.info()
    # other stuff
    test.info()

您将从什么时候开始存储len(self.multiple)作为其自身的值?值得庆幸的是,python在诸如len之类的某些任务上省去了for my_numbers in multiple_numbers:的使用,因此我不需要仅用于迭代。另外,对于类的实例,len的值是静态的,并且在运行时的不同部分(可能)需要多次(因此),因此它不是临时变量like here。通常,这似乎是(非常少量)内存与计算之间的折衷。同样的问题也适用于sum()

部分问题是基于观点的,很高兴听到您对此的看法,但我主要是在寻求有关此问题的约定。

  1. len(self.multiple)应该在什么时候存储为自己的值?
  2. 该名称是否有约定? length_of_multiple_numbers似乎过分膨胀,但具有描述性。
jideyouwo 回答:在python

我会使用局部变量,而不是速度来提高代码的可读性:

@pytest.mark.usefixture("test_setup")
class TestArticleCreation:
    def test_new_article_creation(self):
        art = ArticleCreation(self.driver)
        art.create_new_article()
        article_id = art.get_new_article_id()
        assert art.verify_article_created_in_db(article_id)

局部变量名称可以缩写,因为赋值与使用在同一屏幕上。我使用自己的约定,但通常遵循通用的非正式约定。

我不会尝试将def info(self): n = len(self.multiple) print(f"The length of multiple is {n}") print(f"The length of multiple is {n*4}") print(f"The length of multiple is longer than {n-1}") 分配给len(...)属性,更不用说全局属性了。

基本上,在函数/方法中重复使用的任何值都是局部变量分配的候选对象。

,

我不认为有足够的理由证明存储的合理性,除非每次的计算成本都很高。请参阅hpaulj的答案。

但是,如果您确实想要,可以使用属性,甚至可能对其进行缓存。

class MyList(list):

   @property
   def len_(self):
      return len(self)  #it's a list
or

   _len_ = None

   @property 
   def len_(self):
      if self._len_ is None:
          self._len_ = len(self)
      return self._len_

    def append(self,value):
       self._len_ = None
       super(MyList,self).append(value)

    ...and all other len-modifying methods also need to clear the cache.

同样,如果缓存它,则需要确保每次结果更改时都要重置缓存。这也是您存储在实例变量上的想法的弱点-确保您没有过时的数据所带来的额外复杂性可能只有在您确定这确实是性能瓶颈后才可以接受。

(在您的示例中,multiple_numbers中使用mutable default argument来解决这些问题)。概括地说,如果您的总和/ len取决于可变项的状态,那么存储/缓存计算是一个更糟糕的主意。即,如果MyList引用本身具有len / sum且需要汇总的对象,则MyList不会进行任何缓存/存储业务。

命名方面,我可能会使用semi-convention naming to avoid shadowing built-ins/conventional的名字,即添加一个_cls-> cls_list-> list_

本文链接:https://www.f2er.com/2637923.html

大家都在问