我有一个存放所有.py文件的目录。

bin/
   main.py
   user.py # where class User resides
   dir.py # where class Dir resides

我想在main.py中使用user.py和dir.py中的类。 如何将这些Python类导入main.py? 此外,如果User .py在子目录中,我如何导入User类?

bin/
    dir.py
    main.py
    usr/
        user.py

当前回答

实际上,Python并没有为这种日常用例提供优雅的解决方案。当您正在测试最终将作为Python包的一部分交付的代码时,这尤其成问题。下面是一个对我很有效的方法:

迪尔 |

file1.py file2.py

假设你想从file1导入file2。

# In file1.py:
try:
     # This works when packaged as Python package
     from . import file2
except:
     # This works when simply invoking file1 as a module (i.e. python file1)
     import file2

# rest of the code ...

其他回答

Python3

use

from .user import User inside dir.py file

and

use from class.dir import Dir inside main.py
or from class.usr import User inside main.py

像这样

我刚刚了解到(感谢martineau的评论),为了从同一目录中的文件导入类,你现在可以在Python 3中写道:

from .user import User
from .dir import Dir

Python 3


相同的目录中。

导入文件:log.py

导入类:SampleApp()。

import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

or

目录是最基本的。

导入文件:log.py。

导入类:SampleApp()。

from basic import log
if __name__ == "__main__":
    app = log.SampleApp()
    app.mainloop()

在main.py中:

from user import Class

其中Class是要导入的类的名称。

如果你想调用Class的一个方法,你可以使用:

Class.method

注意,在同一目录下应该有一个空的__init__.py文件。

实际上,Python并没有为这种日常用例提供优雅的解决方案。当您正在测试最终将作为Python包的一部分交付的代码时,这尤其成问题。下面是一个对我很有效的方法:

迪尔 |

file1.py file2.py

假设你想从file1导入file2。

# In file1.py:
try:
     # This works when packaged as Python package
     from . import file2
except:
     # This works when simply invoking file1 as a module (i.e. python file1)
     import file2

# rest of the code ...