如何使函数在被调用时互相知道,例如在使用ElementTree包时。

问题描述 投票:0回答:1

如果标题问题措辞不清楚,下面的代码可以更好的解释。这段代码可以正常工作。

#!/usr/bin/python3
import sys
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import *

country_arg = 'usa'
transport_name_arg = 'train'
route_data = "some route"

world = ET.Element('world')
country = ET.SubElement(world, 'country')
country.text = country_arg
event = ET.SubElement(world, 'event')
transport = ET.SubElement(event, 'transport')
transport.set('name',transport_name_arg)
route = ET.SubElement(event, 'route')

comment = Comment(route_data)
route.append(comment)
c = ET.SubElement(event, 'c')

tree = ET.ElementTree(world)
tree.write("filename.xml")

但是我需要在我的实际脚本的不同地方创建和使用调用它们的函数。我以为,当函数运行时,它和它所代表的代码块运行是一样的。然而似乎function_1的结果没有保存在内存中?下面是和上面一样的脚本,但是代码被分成了两个函数,却无法运行,好像函数_1的结果一被调用函数_2就会丢失。

#!/usr/bin/python3
import sys
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import *

country_arg = 'usa'
transport_name_arg = 'train'
route_data = "some route"

def function_1():
    world = ET.Element('world')
    country = ET.SubElement(world, 'country')
    country.text = country_arg
    event = ET.SubElement(world, 'event')
    transport = ET.SubElement(event, 'transport')
    transport.set('name',transport_name_arg)
    route = ET.SubElement(event, 'route')

def function_2():
    comment = Comment(route_data)
    route.append(comment)
    c = ET.SubElement(event, 'c')

function_1()
function_2()

tree = ET.ElementTree(world)
tree.write("filename.xml")

错误:

Traceback (most recent call last):
  File "test-WITH-functions-xml.py", line 26, in <module>
    function_2()
  File "test-WITH-functions-xml.py", line 22, in function_2
    route.append(comment)
NameError: name 'route' is not defined
python-3.x xml function elementtree
1个回答
0
投票

这段代码很好用,谢谢大家,很好的学习经验。

#!/usr/bin/python3
import sys
import os
import xml.etree.ElementTree as ET
from xml.etree.ElementTree import *

country_arg = 'usa'
transport_name_arg = 'train'
route_data = "some route"

def function_1():
    global world
    global country
    global event
    global transport
    global route
    world = ET.Element('world')
    country = ET.SubElement(world, 'country')
    country.text = country_arg
    event = ET.SubElement(world, 'event')
    transport = ET.SubElement(event, 'transport')
    transport.set('name',transport_name_arg)
    route = ET.SubElement(event, 'route')

def function_2():
    global comment
    global c
    comment = Comment(route_data)
    route.append(comment)
    c = ET.SubElement(event, 'c')

function_1()
function_2()

tree = ET.ElementTree(world)
tree.write("filename.xml")
© www.soinside.com 2019 - 2024. All rights reserved.