简体   繁体   中英

Import a module in Python

I have an improperly packaged Python module. It only has __init__.py file in the directory. This file defines the class that I wish to use. What would be the best way to use it as a module in my script?

** EDIT **

There was a period (.) in the the name of the folder. So the methods suggested here were not working. It works fine if I rename the folder to have a valid name.

That's not improper. It's a package.

http://docs.python.org/2/tutorial/modules.html#packages

package/
    __init__.py
yourmodule.py

In yourmodule.py, you can do either of the following:

import package
x = package.ClassName()

Or:

from package import ClassName
x = ClassName()

__init__.py放入目录my_module ,确保my_modulesys.path ,然后from my_module import WHAT_EVER_YOU_WANT

It's not necessarily improperly packaged. You should be able to do from package import X just like you would normally. __init__.py files are modules just like any other .py file, they just have some special semantics as to how they are evaluated in addition to the normal usage, and are basically aliased to the package name.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM