Warning: file_get_contents(/data/phpspider/zhask/data//catemap/7/python-2.7/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 2.7 Python 2.7.2中不同导入样式的问题_Python 2.7 - Fatal编程技术网

Python 2.7 Python 2.7.2中不同导入样式的问题

Python 2.7 Python 2.7.2中不同导入样式的问题,python-2.7,Python 2.7,我试图模仿Kernighan和Ritchie C编程书中的一些C程序,但在使用getchar()时遇到了问题。我已经让初始程序工作,但是当我将getchar()移动到它自己的文件stdio.py时,它只在声明import stdio后处理调用,如stdio.getchar(),而不是使用**getchar()形式的调用处理声明类型为:from stdio import*的调用 我在FileCopy.py中的工作代码 import stdio import StringIO def FileCo

我试图模仿Kernighan和Ritchie C编程书中的一些C程序,但在使用getchar()时遇到了问题。我已经让初始程序工作,但是当我将getchar()移动到它自己的文件stdio.py时,它只在声明import stdio后处理调用,如stdio.getchar(),而不是使用**getchar()形式的调用处理声明类型为:from stdio import*的调用

我在FileCopy.py中的工作代码

import stdio
import StringIO

def FileCopy():
    c = stdio.getchar()
    while (c!=stdio.EOF):
        stdio.putchar(c)
        c = stdio.getchar()



if __name__ == "__main__":
    SRC = raw_input(">>")
    print "Echoe: ",
    stdio.FP = StringIO.StringIO(SRC)
    FileCopy()
我的stdio.py代码

"""
 Python implementation of getchar
"""

EOF =""

# python specific
import StringIO

FP = None
def getchar():
    if FP:
        return FP.read(1)

def ungetc(c=''):
    if FP:
        FP.seek(-1, os.SEEK_CUR)

def putchar(c):
    print c,
好的,到目前为止还不错。但是,对stdio.getchar()的调用看起来很难看,所以我使用了stdio import*的形式并删除了它们。主要思想是删除所有前缀以提高可读性。没有对stdio.py进行任何更改

"""
File Copy
Kernighan Ritchie page 16
stdio has been created in Python file stdio.py
and defines standard output functions putchar,getchar and EOF
"""

from stdio import *
import StringIO

def FileCopy():
    c = getchar()
    while (c!=EOF):
        putchar(c)
        c = getchar()



if __name__ == "__main__":
    SRC = raw_input(">>")
    print "Echoe: ",
    FP = StringIO.StringIO(SRC)
    FileCopy()
输出

作为FP变量对getchar()的无限调用始终返回NONE。因此,我在输出shell中得到infinate NONE

问题。 为什么第一个示例在stdio.py中初始化FP变量,而第二个示例没有?
有一个简单的修复方法吗?

Python中的全局函数对于一个模块来说是全局的,而不是跨所有模块。在不同的范围内有不同的FPs

您已经想出了一个简单的解决方案。导入模块,以便显式引用模块的变量名

这就是为什么“导入*”不是一个好做法的一个例子

来自官方Python 2.75常见问题解答:


你的建议是“丑陋的”,其他人可能会说是明确和准确的。我希望我能想到的其他选择也会同样丑陋。做丑陋的事情。

Python中的全局函数对于一个模块来说是全局的,而不是跨所有模块。在不同的范围内有不同的FPs

您已经想出了一个简单的解决方案。导入模块,以便显式引用模块的变量名

这就是为什么“导入*”不是一个好做法的一个例子

来自官方Python 2.75常见问题解答:


你的建议是“丑陋的”,其他人可能会说是明确和准确的。我希望我能想到的其他选择也会同样丑陋。做丑陋的事。

这是一个公平的观点,但EOF是C中其他模块的一个全局标准。然而,这一切都可以通过一个类来避免。我真的很喜欢Kernighnan的编程风格,并想使用它!谢谢你的参考。这是一个公平的观点,但EOF是一个全球性的标准。在C中的其他模块。然而,这一切都可以通过一个类来避免。我真的很喜欢Kernighnan的编程风格,并想使用它!谢谢你的推荐。