python - AttributeError:类型对象“数据库”没有属性“初始化”
问题描述
C:\Users\Lenovo\AppData\Local\Programs\Python\Python37-32\fullstack\terminal\Scripts\python.exe C:/Users/Lenovo/AppData/Local/Programs/Python/Python37-32/terminal/mongo1.py
Traceback (most recent call last):
File "C:/Users/Lenovo/AppData/Local/Programs/Python/Python37-32/terminal/mongo1.py", line 5, in <module>
database.initialize()
AttributeError: type object 'database' has no attribute 'initialize'
Process finished with exit code 1
在运行下面的代码后它给了我这个错误请帮助我在 python 编程中仍然是新的我已经检查过但我没有看到我在哪里出错了!
class database(object):
uri = "mongodb://127.0.0.1:27017"
database = None
@staticmethod
def initialize():
client = pymongo.MongoClient(database.uri)
database.database = client["samaz"]
@staticmethod
def insert(collection, data):
database.database[collection].insert(data)
@staticmethod
def find(collection, query):
return database.database[collection].find(query)
@staticmethod
def find_one(collection, query):
return database.database[collection].find_one(query)
解决方案
您需要在类中声明您的方法,如下所示:
class Database:
uri = ...
def __init__(self):
self.client = pymongo.MongoClient(self.uri)
self.database = self.client["samaz"]
对我来说,看起来你也想在类中拥有其他方法,而不使用 @staticmethod 装饰器。它用于不使用类或实例本身的方法,基本上只使用当前类作为命名空间。
推荐阅读
- python - Pandas 中数字范围的分布
- java - 不同类型的排序及其时间
- exception - 为什么 vxworks 寄存器 r3 在执行前被篡改?
- neo4j - Neo4j:从叶子迭代到父对象并找到共同的子对象
- php - 在 PHP 中回显特定的 JSON 节点
- .htaccess - Cloud9 (C9) AWS EC2 .htaccess 被忽略
- flexbox - Object-fit:在 IE 中修复封面灯箱画廊?
- python - 当程序在 Python 中循环时,如何从列表中的用户获取多个输入以进行打印?
- javascript - 补间/动画threejs相机到顶视图
- android - 谷歌地图中的地址位置