python - 全局名称 'doc' 未定义,从一个函数到另一个函数的 vcall 出现问题

标签 python function python-3.x defined

我当前正在编写的一段代码遇到了一些问题。

使用以下代码,我得到 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()

归根结底,这是面向对象编程的完美用例,不是吗?在此之后,可以进行许多良好的改进

例如:

  1. 将函数中的 print 语句替换为外部代码。
  2. 使您的方法可测试。
  3. 单元测试。
  4. 好东西:D

关于python - 全局名称 'doc' 未定义,从一个函数到另一个函数的 vcall 出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19837935/

相关文章:

python-3.x - Pytest - 测试用例执行顺序

regex - Python 3 Pandas 使用 Startswith + 或选择 Dataframe

python - 将 CSV 上传到 Flask 进行后台处理

python - Pandas 每天新专栏

python - 通过spyder运行sympy时摆脱黑色控制台窗口

php - 将 MySQL 查询包装在 PHP 函数中

c - 无法解密函数参数 : pointer and pointer to pointer

javascript - 如何使用 requireJS 从另一个文件调用函数

python-3.x - 使用 python 将 SVG 转换为 PNG?

python - 遵循教程后的 m2m django 实现