Python调用AnimalShelter类create方法缺参数,类初始化问题咨询
问题原因及修复方案
- 核心报错根源:类实例化方式错误。你当前的写法
a = AnimalShelter是将类本身赋值给变量a,而非创建类的实例,手动调用__init__的方式不符合Python类实例化规范,导致调用实例方法时self参数没有被自动传入,系统会把你传入的i当成self参数,因此才会提示data参数缺失。 - 隐藏错误1:
animal_shelter模块中__init__方法缩进错误,self.database = self.client['AAC']现在仅在无用户名密码的else分支中生效,当你传入用户名密码时不会执行这行代码,后续调用方法会找不到database属性报错。 - 隐藏错误2:模块中
update、delete方法里引用的self.AAC是错误写法,应该替换为self.database,否则调用这两个方法时会直接报错。 - 可选优化点:
create方法中使用的insert是pymongo旧版本API,新版本建议替换为insert_one避免弃用警告。
修正后的测试代码
from animal_shelter import AnimalShelter username = "aacuser" password = "Mulligan!23" # 正确实例化类,直接传参即可,不需要手动调用__init__ a = AnimalShelter(username, password) animal_data = [ { "name":"Finn", "type":"dog" }, { "name":"Max", "type":"cat" }, { "name":"Cooper", "type":"dog" }, { "name":"Mulligan", "type":"dog" } ] for i in animal_data: a.create(i) dogs = a.read( {"type":"dog"} ) for dog in dogs: print(dog)
修正后的animal_shelter模块核心代码
from pymongo import MongoClient from bson.objectid import ObjectId class AnimalShelter(object): """ CRUD operations for Animal collection in MongoDB """ def __init__(self, username, password): # Initializing the MongoClient. This helps to # access the MongoDB databases and collections. if username and password: self.client = MongoClient('mongodb://%s:%s@localhost:53937' % (username,password)) else: self.client = MongoClient('mongodb://localhost:53937') # 调整缩进到if else分支外,所有场景都初始化database self.database = self.client['AAC'] # Complete this create method to implement the C in CRUD. def create(self, data): if data is not None: # 替换为新API insert_one insert = self.database.animals.insert_one(data) # data should be dictionary if insert.acknowledged: return True else: return False else: raise Exception("Nothing to save, because data parameter is empty") # Create method to implement the R in CRUD. def read(self,criteria=None): # If data applicable, it will return all rows which match criteria if criteria: # {'_id':False}, no ID will be placed in row(s) data = self.database.animals.find(criteria,{"_id":False}) else: data = self.database.animals.find( {} , {"_id":False}) return data # Create method to implement the U in CRUD def update(self, data, newData): if data is not None: # 修正为self.database return self.database.animals.update_one(data, {'$set': newData}) else: print("Nothing to update, because data parameter is empty") return False # Create method to implement the D in CRUD def delete(self, data): if data is not None: # 修正为self.database,调整print位置到return之前 res = self.database.animals.delete_one(data) print("data deleted") return res else: return False
内容的提问来源于stack exchange,提问作者sarahprince23
相关产品推荐
相关产品推荐

