I have two files: a.py b.py
How can I access my ABC123 class defined in a.py from b.开发者_C百科py?
import a
x = a.ABC123()
or
from a import ABC123
x = ABC123()
will do the job, as long as a.py
and b.py
are in the same directory, or if a.py
is in a directory in sys.path
or in a directory in your environment's $PYTHONPATH
. If neither of those is the case, you might want to read up on relative imports in PEP328.
In spite of being several years old, Importing Python Modules might be worth reading for a more thorough overview of importing from other modules. It does seem beginner-friendly, too.
You need to import the objects from the other file:
from a import ABC123
For a good discussion on this topic please see Importing Python Modules:
The import and from-import statements are a constant cause of serious confusion for newcomers to Python. Luckily, once you’ve figured out what they really do, you’ll never have problems with them again.
This note tries to sort out some of the more common issues related to import and from-import and everything.
精彩评论