[英]Can't instantiate Python class even though it's being imported
I'm writing a Python package that looks like this: 我正在编写一个如下所示的Python包:
|- datum/
|- __init__.py
|- database.py
__init__.py __init__.py
from .database import Database
def connect(url):
print(Database) # for debugging
return Database(url)
database.py database.py
class Database(object):
def __init__(self, url):
self.url = url
...more methods
This is installed as a package called datum
in development mode. 它在开发模式下作为名为
datum
的包安装。 If I call connect
outside of this package like: 如果我在这个包之外调用
connect
,如:
import datum
db = datum.connect('postgresql://xxx')
...this is the output: ......这是输出:
<class 'datum.database.Database'>
Traceback (most recent call last):
File "Z:\AIS\Flask\ais\engine\scripts\load_pwd_parcels.py", line 30, in <module>
source_db = Database(source_db_url)
NameError: name 'Database' is not defined
I'm confused because the class is being imported fine -- I can print it and even run dir
on it and see all my methods -- but when I try to instantiate something it's "not defined". 我很困惑,因为这个类被正确导入 - 我可以打印它,甚至可以在它上面运行
dir
并查看我的所有方法 - 但是当我尝试实例化某些内容时,它“未定义”。 Does anyone know what I'm doing wrong here? 有谁知道我在这里做错了什么?
A NameError
means that a local or global name cannot be found. NameError
表示无法找到本地或全局名称。 I would make sure that your "load_pwd_parcels.py" file includes: 我会确保你的“load_pwd_parcels.py”文件包括:
from database import Database
Alternatively, you could do: 或者,您可以这样做:
import database
source_db = database.Database(source_db_url)
The latter option is a great choice because it gives database
its very own namespace. 后一个选项是一个很好的选择,因为它为
database
了自己的命名空间。 In the words of Tim Peters in PEP 20 -- The Zen of Python : "Namespaces are one honking great idea - let's do more of those!" 用PEP 20中的蒂姆·彼得斯的话来说- “禅宗的Python” :“命名空间是一个很棒的主意 - 让我们做更多的事情吧!”
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.