首页 > 解决方案 > 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)

标签: pythonmongodb

解决方案


您需要在类中声明您的方法,如下所示:

class Database:
    uri = ...

    def  __init__(self):
        self.client = pymongo.MongoClient(self.uri)
        self.database = self.client["samaz"]

对我来说,看起来你也想在类中拥有其他方法,而不使用 @staticmethod 装饰器。它用于不使用类或实例本身的方法,基本上只使用当前类作为命名空间。


推荐阅读