我当前正在编写的一段代码遇到了一些问题。
使用以下代码,我得到 NameError: global name 'doc' is not Defined。
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
def createTitle():
print (t[0], file=doc) #<!DOCTYPE html>
print (t[1], file=doc) #<html>
print (t[2], file=doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=doc) #</head>
我知道这是因为该文档仅在 createHtml 函数中定义。但是,如果我希望同一个文档在不同的函数中调用时也能工作,我该如何让它工作呢?我不能将它排除在 createHtml 函数之外,因为它会弄乱我的程序,因为我有一个菜单允许用户从不同的功能中进行选择。 像这样:
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
createHtml()
elif menu == "2":
createTitle()
elif menu == "3":
createBody()
else:
print ("Good bye!")
break
doc.close()
文档由名称变量定义:
name = input("\nEnter the name for your HTML-page: ")
有没有办法从 createHtml 函数获取文档到我的其他函数?
最佳答案
将函数包装在类中怎么样?
class HtmlBuilder(object):
def __init__(self):
self.doc = None
def createHtml(self):
name = input("\nEnter the name for your HTML-page: ")
self.doc = open(name + ".html", 'w')
def createTitle(self):
print (t[0], file=self.doc) #<!DOCTYPE html>
print (t[1], file=self.doc) #<html>
print (t[2], file=self.doc) #<head>
title = input("Enter your title here: ")
print (" <title>",title,"</title>", file=doc)
print (t[3], file=self.doc) #</head>
def Dispose(self):
self.doc.flush()
self.doc.close()
然后像这样使用它:
hb = HtmlBuilder()
while True:
menu = input("\nPress 1 to enter the file name for the HTML-page"
"\nPress 2 to enter title for the HTML-page"
"\nPress 3 to start entering code in body"
"\nPress 4 to exit\n")
if menu == "1":
hb.createHtml()
elif menu == "2":
hb.createTitle()
elif menu == "3":
hb.createBody()
else:
print ("Good bye!")
break
hb.Dispose()
归根结底,这是面向对象编程的完美用例,不是吗?在此之后,可以进行许多良好的改进。
例如:
- 将函数中的
print
语句替换为外部代码。 - 使您的方法可测试。
- 单元测试。
- 好东西:D
关于python - 全局名称 'doc' 未定义,从一个函数到另一个函数的 vcall 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837935/