简体   繁体   English

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

[英]Global vs local instances in Python

I'm a self-taught programmer without much CS background. 我是一个没有太多CS背景的自学成才的程序员。 I read a lot of discussions here about the topic of global variables in Python, but I'm still unclear about when the use of global is 'good programming practice'. 我在这里阅读了很多有关Python中的全局变量主题的讨论,但是我仍然不清楚何时使用全局是“良好的编程习惯”。

Let's assume I write a Python script that performs a couple of long computations on each sample in a folder. 假设我编写了一个Python脚本,该脚本对文件夹中的每个样本执行了几次长时间的计算。 I create a simple class that holds the results of each computation, so once the script is finished I can print a summary file. 我创建了一个简单的类,其中包含每个计算的结果,因此一旦脚本完成,我就可以打印摘要文件。

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

I see 2 ways to write the main script: 我看到两种编写主脚本的方式:

A) Using the global statement: 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) Without the global statement, passing the instance to the function: 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()

Especially when I have several types of Info classes and many LongComputation functions, option B) becomes very messy. 特别是当我有几种类型的Info类和许多LongComputation函数时,选项B)变得非常混乱。 On the other hand, using the global statement is discouraged. 另一方面,不建议使用全局语句。

Should I use B) over A)? 我应该在A)上使用B)吗? Why? 为什么?

I don't see why you need to use a global here, you can just compute and return the value before adding it to the Info object. 我不明白为什么需要在这里使用全局变量,您可以在将值添加到Info对象之前先进行计算并返回它。 Also the class is overkill when a simple dictionary works just fine. 当一个简单的字典工作得很好时,该类也是多余的。

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()

When to use globals: 何时使用全局变量:

  1. when it's a constant 当它是一个常数
  2. when it's a singleton 当是单身时
  3. when it's a private cache 当它是私人缓存时

And maybe, when your script is a quick, throwaway hack ;-) 也许,当您的脚本是一种快速,简单的技巧时;-)

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

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