我确信这个问题在某处有答案,但我似乎找不到合适的搜索词来找出答案
源文件布局:
./mycode.py
./protocols/__init__py (empty)
./protocols/prot1.py
./protocols/prot2.py
./protocols/prot3.py
./协议/prot1.py:
class Prot1:
@classmethod
def getAddress(cls, data):
return f(data)
Prot2和Prot3类似,但返回值在每个类中的计算方式不同
mycode.py码:
import protocols
self.protocolClasses = {
"1" : Prot1,
"2" : Prot2,
"3" : Prot3
}
protocol = "1" # just for the example
f = self.protocolClasses[protocol].getAddress(somedata)
在我看来这是对的,但Python给出了一个错误:
NameError: global name 'Prot1' is not defined
引用的行号为:
"1" : Prot1,
我错过了什么
编辑:如果使用以下语法:
"1" : protocols.prot1.Prot1,
我得到:
AttributeError: 'module' object has no attribute 'prot1'
如果我使用:
"1" : protocols.Prot1,
我得到:
AttributeError: 'module' object has no attribute 'Prot1'
拥有你的目录结构,你必须修复导入
以下是可行的方法:
或者可以使用
./protocols/__init__py
并在其中添加下一行:这样,您就可以进行如下导入:
为什么会这样
这是因为
protocols
是一个Python包(其中包含__init__.py
文件),而prot1
、prot2
、prot3
是Python模块。在这些模块中,您定义了类。这就是为什么需要使用完整的名称空间,即protocols.prot1.Prot1
或from protocols.prot1 import Prot1
相关问题 更多 >
编程相关推荐