How to import and create my class from my module?
I am creating a module, it has the classes:
class LogLevel():
Info = 1
Warn = 2
Error = 3
class FalconPeer():
def __init__(self, port=37896, log_level=LogLevel.Info):
self._port = port
self._log_level = log_level
In the folder structure:
+---PyFalconUDP | CHANGES.txt | LICENSE.txt | MANIFEST.in | README.txt | setup.py | +---falconudp | enums.py | falconpeer.py | tree.txt | __init__.py | +---test | test_location.py | test_utils.py | __init__.py
But running Python in the PyFalconUDP folder I cannot import and use my classes - how do I create a FalconPeer
?
Python 3.3.2 (v3.3.2:d047928ae3f6, May 16 2013, 00:03:43) [MSC v.1600 32 bit (In tel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> import falcondup.FalconPeer Traceback (most recent call last): File "", line 1, in ImportError: No module named 'falcondup' >>> import falconudp.FalconPeer Traceback (most recent call last): File "", line 1, in ImportError: No module named 'falconudp.FalconPeer' >>> import falconudp >>> a = FalconUDP() Traceback (most recent call last): File "", line 1, in NameError: name 'FalconUDP' is not defined >>> a = falconudp.FalconPeer() Traceback (most recent call last): File "", line 1, in AttributeError: 'module' object has no attribute 'FalconPeer' >>> from falconudp import FalconPeer Traceback (most recent call last): File "", line 1, in ImportError: cannot import name FalconPeer >>>
Break down your details:
Pkg : falcondup
Module: falconpeer
Class : FalconPeer
Import using the module name:
import falcondup.falconpeer
Create an object using the full path till the class name:
obj = falcondup.falconpeer.FalconPeer()
Once you created the obj, you can call all the method inside the class.
Calling method inside class:
obj.method_name()
And if you want to access class attribute, by using the class name.
falcondup.falconpeer.LogLevel.Info
falcondup.falconpeer.LogLevel.Warn
falcondup.falconpeer.LogLevel.Error
If you want to use inside : class_name.class_var_name
Another scenerio:
if you LogLevel class are in different file which mean different modules, then you need to import that module than you can access it.
To import something from your falconudp module, it should be in the global namespace of __init__.py
.
So the class declarations should either:
__init__.py
, or import falconpeer
inside __init__.py
下一篇: 如何从我的模块导入和创建我的课程?