创建Python类字典

2024-09-30 02:15:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我确信这个问题在某处有答案,但我似乎找不到合适的搜索词来找出答案

源文件布局:

./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'

Tags: 答案pyselfdataprotocolattributeerrormoduleprotocols
1条回答
网友
1楼 · 发布于 2024-09-30 02:15:29

拥有你的目录结构,你必须修复导入

以下是可行的方法:

from protocols.prot1 import Prot1
from protocols.prot2 import Prot2
from protocols.prot3 import Prot3

self.protocolClasses = {
    "1"  : Prot1,
    "2"  : Prot2,
    "3"  : Prot3
}

protocol = "1"  # just for the example
f = self.protocolClasses[protocol].getAddress(somedata)

或者可以使用./protocols/__init__py并在其中添加下一行:

from prot1 import Prot1
from prot2 import Prot2 
from prot3 import Prot3

这样,您就可以进行如下导入:

from protocols import Prot1, Prot2, Prot3

为什么会这样

这是因为protocols是一个Python包(其中包含__init__.py文件),而prot1prot2prot3是Python模块。在这些模块中,您定义了类。这就是为什么需要使用完整的名称空间,即protocols.prot1.Prot1from protocols.prot1 import Prot1

相关问题 更多 >

    热门问题