我正在编写一段代码时遇到了一些问题。
使用下面的代码,我得到了NameError:未定义全局名称'doc‘。
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>我知道这是因为doc只在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变量定义了doc:
name = input("\nEnter the name for your HTML-page: ")还有从createHtml-函数到我的其他函数的doc吗?
发布于 2013-11-07 14:14:44
如何将函数包装在类中呢?
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语句替换为外部代码。发布于 2013-11-07 14:13:43
您的函数createHtml()函数将需要return doc,然后可以将其传递给createTitle()。就像这样:
def createHtml():
name = input("\nEnter the name for your HTML-page: ")
doc = open(name + ".html", 'w')
return doc那么在then循环中:
doc = createHtml()然后您可以将它传递给其他函数:
createTitle(doc)请注意,在每个函数中不需要调用相同的东西。
https://stackoverflow.com/questions/19837935
复制相似问题