简体   繁体   English

在脚本中使用全局变量

[英]Use of global variables in script

I threw the 'Apple-code' in the trash, please look at the following code : 我把“苹果代码”丢进了垃圾箱,请看下面的代码:

# Define processing inputted line
def inputfile(line):
    linecontents = { 'item_0110':   line[0:8],
                     'item_0111':   line[8:16],
                     'item_0112':   line[16:24] }
    print 'In the function : ', linecontents
    print 'In the function : ', len(linecontents)

# Set dictionary
linecontents = {}

# Pretend to open a file and read line for line
line = '010012343710203053525150'

# Start processing the read line
inputfile(line)

# Display end resultprint
print '\nOutside the function : ', linecontents
print 'Outside the function : ', len(linecontents)

Ok, first off : I'm an idiot for trying this with vars. 好的,首先:我是一个用vars尝试的白痴。 In the original post I already stated I have more than thirty items (fields if you want) in the file. 在原始帖子中,我已经说过文件中有三十多个项目(如果需要,则为字段)。 To make matters more complex, a line from the file could look like this : 为了使事情更复杂,文件中的一行可能看起来像这样:

010012343710203053525150

And not all lines have the same fields so depending on what type of field it is, I would like to call a different function. 并不是所有的行都具有相同的字段,因此根据字段的类型,我想调用其他函数。

The question now is : why is the output like this : 现在的问题是:为什么输出是这样的:

In the function :  {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
In the function :  3

Outside the function :  {}
Outside the function :  0

I thought the dictionary is independent from functions and/or classes ? 我以为字典独立于函数和/或类?

There are some issues with your code. 您的代码存在一些问题。 I don't really see the see for global variables here. 我在这里真的看不到全局变量的see。

I reformatted and refactored your code (no uppercase except for classes). 我重新格式化并重构了您的代码(除类外,没有大写字母)。 You intent is not clear so I tried my best. 您的意图不明确,所以我尽力了。 The function read_file actually reads you file line by line and returns customer_name and customer_item line by line. 函数read_file实际上read_file读取您的文件,并逐行返回customer_namecustomer_item

def read_file(filepath):
    with open(filepath) as customer_file:
        for line in customer_file:
            customer_name = line[:10]
            customer_item = line[10:]
            print('Name : ' + customer_name)
            print('Item : ' + customer_item)
            yield customer_name, customer_item

In the main() or whatever function, you can do what you want with the customer's variables. main()或任何函数中,您可以使用客户的变量进行所需的操作。

What is important here, is that read_file actually reads a file and process the information for the file before returning them to the calling function. 在这里重要的是, read_file实际上会读取文件并处理该文件的信息,然后再将其返回给调用函数。

def main():
    myfile = 'CustomerFile.txt'
    for customer_name, customer_item in read_file(myfile):
        if customer_item == 'Apple':
            print(customer_name)
        else:
            print(customer_name + ' is not eating an apple')

Instead of using globals, let the ReadFile function return the values 不要使用全局变量,而应使用ReadFile函数返回值

def ReadFile(line):
    ...
    return CustomerName, CustomerItem

and assign them to variables after calling the function: 并在调用函数后将它们分配给变量:

for line in CustomerFile:
    CustomerName, CustomerItem = ReadFile(line)

def ReadFile(line):
    CustomerName = line[0:10]
    CustomerItem = line[10:]
    return CustomerName, CustomerItem

def Report(CustomerName, CustomerItem):   
    # Try to keep all print statements in one place
    print 'Name : ' + CustomerName
    print 'Item : ' + CustomerItem
    if CustomerItem == 'Apple':
        print CustomerName
    else:
        print CustomerName + ' is not eating an apple'

with open(CustomerFile.txt) as CustomerFile:
    for line in CustomerFile:
        CustomerName, CustomerItem = ReadFile(line)
        Report(CustomerName, CustomerItem)

Note that the PEP8 style guide recommends using lower_case for variable and function names and to reserve CamelCase for classes. 请注意, PEP8样式指南建议为变量和函数名称使用lower_case,并为类保留CamelCase。 While you are free to use your own style, use of PEP8 is quite prevalent and so by joining the PEP8-club your code will more naturally "fit in" with other people's code and vice-versa. 尽管您可以自由使用自己的样式,但是PEP8的使用非常普遍,因此,通过加入PEP8-club,您的代码将更自然地“适合”他人的代码,反之亦然。

I found the (obvious) answer. 我找到了(显而易见的)答案。 As I said, my Python is a bit rusty : 如我所说,我的Python有点生锈:

## Define processing inputed line
#
def inputfile(line, linecontents):
    linecontents['item_0110'] = line[0:8]
    linecontents['item_0111'] = line[8:16]
    linecontents['item_0112'] = line[16:24]
    print 'In the function : ', linecontents
    print 'In the function : ', len(linecontents)

## Define main script
#
def main():
    # Set dict
    linecontents = {}

    # Pretend to open a file and read line for line
    line = '010012343710203053525150'

    # Start processing the read file
    inputfile(line, linecontents)

    # Display end resultprint
    print '\nOutside the funtion  : ', linecontents
    print 'Outsude the function : ', len(linecontents)


## Start main script
#
main()

And this neatly returns : 整齐地返回:

In the function :  {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
In the function :  3

Outside the funtion  :  {'item_0112': '53525150', 'item_0111': '37102030', 'item_0110': '01001234'}
Outsude the function :  3

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

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