繁体   English   中英

Python中的全局实例与本地实例

[英]Global vs local instances in Python

我是一个没有太多CS背景的自学成才的程序员。 我在这里阅读了很多有关Python中的全局变量主题的讨论,但是我仍然不清楚何时使用全局是“良好的编程习惯”。

假设我编写了一个Python脚本,该脚本对文件夹中的每个样本执行了几次长时间的计算。 我创建了一个简单的类,其中包含每个计算的结果,因此一旦脚本完成,我就可以打印摘要文件。

class SampleInfo():

    def __init__(self):
        self.dict = {}

    def add_sample(self, sample):
        self.dict[sample] = {}

    def add_value(self, sample, value)
        self.dict[sample] = value

我看到两种编写主脚本的方式:

A)使用全局语句:

import os

def LongComputation(sample):
    # do some stuff that results in a value
    Info.add_value(sample, value)

def main():
    global Info
    Info = SampleInfo()
    for sample in os.listdir("."):
        LongComputation(sample)

main()

B)如果没有全局语句,则将实例传递给函数:

import os

def LongComputation(sample, info_instance=None):
    # do some stuff that results in a value
    info_instance.add_value(sample, value)

def main():
    Info = SampleInfo()
    for sample in os.listdir("."):
        LongComputation(sample, info_instance=Info)

main()

特别是当我有几种类型的Info类和许多LongComputation函数时,选项B)变得非常混乱。 另一方面,不建议使用全局语句。

我应该在A)上使用B)吗? 为什么?

我不明白为什么需要在这里使用全局变量,您可以在将值添加到Info对象之前先进行计算并返回它。 当一个简单的字典工作得很好时,该类也是多余的。

import os

def LongComputation(sample):
    # do some stuff that results in a value
    return value

def main():
    Info = {}
    for sample in os.listdir("."):
        Info[sample] = LongComputation(sample)

main()

何时使用全局变量:

  1. 当它是一个常数
  2. 当是单身时
  3. 当它是私人缓存时

也许,当您的脚本是一种快速,简单的技巧时;-)

暂无
暂无

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

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