AttributeError: 'AnimalShelter' object has no attribute 'database'

AttributeError: 'AnimalShelter' object has no attribute 'database'

我不明白为什么会收到此错误,因为我的 .py 文件表明数据库实际上是一个属性。我已确保所有内容都按应有的方式缩进,并确保在导入 AnimalShelter 时标记了正确的 .py。我正在关注 class 的演练,.ipynb 肯定详细说明了演练中的所有内容,因此 .py 文件一定有问题。我只是不明白什么...

from jupyter_plotly_dash import JupyterDash
import dash
import dash_leaflet as dl
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import dash_table
from dash.dependencies import Input, Output
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from pymongo import MongoClient
#### FIX ME #####
# change animal_shelter and AnimalShelter to match your CRUD Python module file name and class name
from AAC import AnimalShelter

###########################
# Data Manipulation / Model
###########################
# FIX ME update with your username and password and CRUD Python module name
username = "aacuser"
password = "monogoadmin"
shelter = AnimalShelter(username, password)
# class read method must support return of cursor object and accept projection json input
df = pd.DataFrame.from_records(shelter.read({}))

print (df)
import pymongo
from pymongo import MongoClient
from bson.objectid import ObjectId

class AnimalShelter(object):
    """CRUD operations for Animal collection in Mongodatabase"""
    #Initializes MongoClient
    def _init_(self, username, password):
        self.client = MongoClient('mongodb://127.0.0.1:38574' % (username, password))
        self.database = self.client['project']  
    #Implement create method
    def create(self, data):
        if data is not None:
            return self.database.animals.insert_one(data)
        else:
            raise Exception("Nothing to save, because data parameter is empty")
    #Implement read method
    def read(self, data):
        if data is not None:
            return self.database.animals.find(data)
        else:
            raise Exception("Nothing to read, because data parameter is empty")
    #Implement update method
    def update(self, data):
        if find is not None:
            return self.database.animals.update_one(data)
        else:
            raise Exception("Nothing to update, because data parameter is empty")
    #Implement delete method
    def delete(self, data):
        if data is not None:
            return self.database.animals.delete_one(data)
        else:
            raise Exception("Nothing to delete, because data parameter is empty")
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-11-2eb0b77f93e5> in <module>
     23 shelter = AnimalShelter()
     24 # class read method must support return of cursor object and accept projection json input
---> 25 df = pd.DataFrame.from_records(shelter.read({}))
     26 
     27 print (df)

~/Desktop/AAC.py in read(self, data)
     18 def read(self, data):
     19         if data is not None:
---> 20                 return self.database.animals.find(data)
     21         else:
     22                 raise Exception("Nothing to read, because data parameter is empty")

AttributeError: 'AnimalShelter' object has no attribute 'database'

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-1-fdaad3d4f048> in <module>
     21 username = "aacuser"
     22 password = "monogoadmin"
---> 23 shelter = AnimalShelter(username, password)
     24 # class read method must support return of cursor object and accept projection json input
     25 df = pd.DataFrame.from_records(shelter.read({}))

~/Desktop/AAC.py in __init__(self, username, password)
      7         #Initializes MongoClient
      8         def __init__(self, username, password):
----> 9                 self.client = MongoClient('mongodb://127.0.0.1:38574' % (username, password))
     10                 self.database = self.client['project']
     11         #Implement create method

TypeError: not all arguments converted during string formatting

您需要将 _init_ 更改为 __init__:

改变

#Initializes MongoClient
def _init_(self, username, password):
    self.client = MongoClient('mongodb://127.0.0.1:38574' % (username, password))
    self.database = self.client['project']

#Initializes MongoClient
def __init__(self, username, password):
    self.client = MongoClient('mongodb://127.0.0.1:38574' % (username, password))
    self.database = self.client['project']  

当您调用 AnimalShelter(...) 时,Python 会尝试调用 __init__(如果存在),如果不存在,则使用默认实现。它不会自动调用 _init_.

因此,self.database = self.client['project'] 永远不会被执行,所以 AnimalShelter 没有 database 属性,这就是您出错的原因。