【问题标题】:Importing modules Python导入模块 Python
【发布时间】:2014-07-15 21:44:33
【问题描述】:

嘿,我在弄清楚这段代码中要求导入的内容时遇到了一些麻烦

#!/opt/local/bin/python

import sys
from formatter import Formatter

def main():
#do stuff

在我的类 formatter.py 中,我是否必须定义一个名为 Formatter 的函数。对此有点困惑。我一直在通过放置

来测试我的代码
from formatter import *

它采用了我课堂上的所有定义(我相信)。

【问题讨论】:

  • formatter.py 是一个模块,而不是一个类,按照惯例,Formatter 将是一个类,而不是一个函数。但是,是的,你会用这个名字创建一些东西。
  • docs.python.org/3/reference/simple_stmts.html#import 文档是一个很好的起点。在去 SO 之前,你应该总是谷歌。

标签: python module python-import


【解决方案1】:

您的from formatter import Formatter 行将在模块格式化程序中搜索名称为Formatter 的任何内容。 因此,如果您在该模块中有一个名为 Formatter 的函数,它将被导入,这意味着您可以在主要部分中使用它(导入行下方的任何地方都可以使用) 它也将导入类。

formatter.py 是一个模块。一个类可能看起来像:

class A:
    variable = 1
    def b():
        #do stuff

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-10-06
    • 2016-12-15
    • 1970-01-01
    • 2023-04-05
    • 2018-04-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多