如何在python类继承中使用super()

时间:2015-05-04 11:51:09

标签: python inheritance super

我尝试按super() SO {答案}实施class Collection(): """returns a collection curser from mongodb""" def __init__(self, db, collection_name): self.db = db self.collection_name = collection_name if not hasattr(self.__class__, 'client'): self.__class__.client = MongoClient() self.data_base = getattr(self.client, self.db) self.collection = getattr(self.data_base, self.collection_name)

我有以下课程:

class User(Collection):
    def __init__(self, db, collection_name):
        super(User, self).__init__(db, collection_name)

以及以下子类:

Collection

调用agents = Collection('hkpr_restore','agents') 类可以正常工作:

user = User('hkpr_restore','agents')

调用子类:

Traceback (most recent call last):
  File "main.py", line 37, in <module>
    user = User('hkpr_restore','agents')
  File "filepath/user.py", line 35, in __init__
    super(User, self).__init__(db, collection_name)
TypeError: must be type, not classobj

我收到错误:

    @RequestMapping(value="/saveCli")
public String saveCli(@Valid Client c,BindingResult bindingResult, Model model){
    if(bindingResult.hasErrors()){
        model.addAttribute("clients",metier.listClients());
        return ("creerClient");
    }
    if(c.getIdClient()!=null){
    metier.modifierClient(c);

    }else

    metier.ajouterClient(c);
    model.addAttribute("client", new Client());
    model.addAttribute("clients",metier.listClients());
    return "creerClient";

}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

Collection(object)之类的对象继承Collection以创建新的样式类。这样,super就可以工作了(它只适用于新的样式类)。

相关问题