所以我编写了我的第一个python脚本(test.py),现在我想在控制台上为函数test1调用docstring,但没有运气
我的剧本:
import os
os.system('cls')
def test1 (a , b ):
"""
Learning Python to make a better world
This is my first program
"""
c = a+b
print (c)
test1(1,2)
print (test1.__doc__)
但是当我在控制台上导入脚本时,这就是我得到的
C:\Python34\python.exe 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:44:40) [MSC v.1600 64 bit (AMD64)]
import test
print(test1.__doc__)
Traceback (most recent call last):
File "<input>", line 1, in <module>
NameError: name 'test1' is not defined
print(test.test1.__doc__)
Traceback (most recent call last):
File "<input>", line 1, in <module>
AttributeError: 'module' object has no attribute 'test1'
不确定我在这里做错了什么,一定是非常基本的。
答案 0 :(得分:1)
你肯定会导入一些test
模块,这些模块存在于由其他Python软件包安装的真实python中,而不是你的test.py
。在这种简单的情况下,您需要从与python
相同的目录运行test.py
并验证test
模块是否实际导入,如果相对导入它应该如下所示:
>>> import test
>>> print(test)
<module 'test' from 'test.pyc'>
否则会显示如下内容:
>>> import test
>>> print(test)
<module 'test' from '/usr/lib/python3.4/test/__init__.py'>
最佳做法是,不要使用test.py为临时模块命名,保留单元/功能测试。
答案 1 :(得分:1)
Python3有一个test
模块,仅供内部使用。请参阅:https://docs.python.org/3.4/library/test.html
因此,如果您将脚本保存到名为test.py
的文件中,则导入该脚本的唯一方法是在与test.py脚本相同的目录上运行python console。只需将文件名更改为mytest.py
,然后执行import mytest
和print(mytest.test1.__doc__)
即可避免出现问题。