在python中将len()和sum()存储为变量的约定

Fin*_*inn 2 python conventions

是否有关于何时以及如何在 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()
Run Code Online (Sandbox Code Playgroud)

你会在什么时候开始存储len(self.multiple)它自己的价值?值得庆幸的是,python 在len某些任务中for my_numbers in multiple_numbers:不使用 ,所以我不需要它只用于迭代。此外,len对于类的实例, 的值是静态的,并且在运行时的不同部分(可能)多次需要,所以它不是像这里的临时变量 。一般来说,这似乎是(非常少量的)内存与计算之间的权衡。同样的问题适用于sum().

这些问题的一部分是基于意见的,我很高兴听到您的想法,但我主要是在寻找关于此的约定。

  1. 在什么时候,如果有的话,应该len(self.multiple)作为它自己的值存储?
  2. 名称有约定吗?length_of_multiple_numbers看起来臃肿,但会是描述性的。

hpa*_*ulj 5

我会使用局部变量,更多的是为了代码可读性而不是速度:

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}")
Run Code Online (Sandbox Code Playgroud)

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

我不会尝试分配len(...)self属性,更不用说全局了。

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