Python 从另一个文件导入类及其函数
我在用python导入类方面没有什么问题。我的工作流程是这样的Python 从另一个文件导入类及其函数,python,class,Python,Class,我在用python导入类方面没有什么问题。我的工作流程是这样的 index.py class Template: def header(): def body(): def form(): def footer(): display.py 我想在我的display.py页面中调用函数header()、body()和footer()。有谁能用python向我解释一下这个问题吗。谢谢你的关心 索引文件---[Index.
index.py
class Template:
def header():
def body():
def form():
def footer():
display.py
我想在我的display.py
页面中调用函数header()
、body()
和footer()
。有谁能用python向我解释一下这个问题吗。谢谢你的关心
索引文件---[Index.py][1]
[1] :和display.py--“”我不确定是否正确理解您的意思,但我相信您正在询问如何在另一个脚本中导入
模板
类。import
语句就是您所需要的:
from index import template
foo = template()
foo.header()
foo.body()
foo.footer()
你试过什么?以下是导入后使用
Template
class方法的正常方式
from index import Template
t = Template()
t.header()
t.body()
t.footer()
ETA:在
index.py
文件的末尾(第99-105行),您正在调用上述定义的模板
类中的所有函数。这就是您看到重复的原因。编辑:好的,我知道您的问题是什么,给定了您的代码
您正在呼叫以下用户:
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
objx.Header()
objx.Body()
objx.Form()
objx.Footer()
objx.CloseHtml()
然后在display.py中:
t = HtmlTemplate()
t.Header()
t.Body()
cgitb.enable()
print 'Content-type: text/html\n\n'
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/msa.css\" >"
# [...]
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
# [...]
objx.CloseHtml()
查看如何调用Body()
两次
作为一个脚注,您应该像现在这样对方法名使用小写,对类使用大写。这是一个很好的会议。我极力推荐它
只需在display.py
中构造一次对象并调用所有方法。在index.py的顶部和底部都有以下代码:
t = HtmlTemplate()
t.Header()
t.Body()
cgitb.enable()
print 'Content-type: text/html\n\n'
print "<link rel=\"stylesheet\" type=\"text/css\" href=\"css/msa.css\" >"
# [...]
## Calling all the functions of the class template with object (objx)
objx=HtmlTemplate()
# [...]
objx.CloseHtml()
…或者最好还是把这些代码函数放在可以从其他地方调用的地方。在索引文件的底部创建一个HtmlTemplate
对象并调用其上的所有方法。由于此代码不包含在任何其他块中,因此在导入模块时将执行此代码。您需要删除它,或者检查文件是否正在从命令行运行
if __name__ == "__main__":
objx=HtmlTemplate()
objx.Header()
objx.Body()
objx.Form()
objx.Footer()
objx.CloseHtml()
以下解决方案对我有效:
class1(unittest.TestCase):
def method1(self)
class2(unittest.TestCase):
def method2(self):
instance_name = class1("method1")
instance_name.method1()
这里有几个拼写错误,这使得你的答案完全没有意义。@Sil:我的答案的第一次修订确实有问题。如果不是因为烦人的“你是人类”特性,在你发表评论之前就已经纠正了错误:)我建议你阅读更多的Python教程。有很多例子<代码>=]
另外,请注意Python样式指南()建议在类名中使用大写字母,而不是所有小写字母。谢谢您的代码!我们不可能想出别的办法。现在去接受更多的答案=3我也像你一样试过。但我总是重复两次身体()etc@user:您可能正在从模板的\uuuu init\uuuu
调用方法。否则,这段代码中并没有任何东西会产生重复。是的,每个函数都有自己的参数,我知道你们还有什么问题?你能给我们提供更多的代码吗?就像我上面的工作流程一样,我有index.py文件[带有给定的类和函数],从index.py文件我想把值从form()传递到display.py。在display.py中,我只需要调用header()、body()和footer()。但我正在做和你们说的一样的事情,但是在显示页面上有重复。显示页面如下所示-header()、body()、form()、footer()以及显示页面中的body()和其他内容。@用户:我们需要查看模板类及其方法的实际代码。我们不是通灵者。@user343934:如果你调用body()
两次,那么你肯定期望body()
的输出两次……它似乎可以工作,但仍然有一个错误,那就是在display.py中,我在topYes上收到了“Content type:text/html”。。。该代码也与模块一起拉入。我已经在修改后的答案中包含了这一点。@user343934:是的,因为您应该将内容类型也放入HTML正确的语法中。