【问题标题】:how to user super() in python class inheritance [duplicate]如何在python类继承中使用super()[重复]
【发布时间】:2015-05-04 11:51:08
【问题描述】:

我正在尝试按照this SO 答案实施super()

我有以下课程:

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

我做错了什么?

【问题讨论】:

  • 您可能想要使用Collection.client = ... 而不是self.__class__.client = ...,这样每个子类共享同一个客户端,并且您使用的连接更少。您也可以使用全局名称而不是类属性。
  • 如果你使用的是 Python 2,你应该在你的问题中添加一个 Python 2 标签。

标签: python inheritance super


【解决方案1】:

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

【讨论】:

  • FWIW,Python 3 中的所有类都是新式的,因此在 Python 3 中不需要显式地从 object 继承。OTOH,在 Python 3 中编写 object 并没有什么坏处,我想在实用的情况下编写在 Py 2 和 Py 3 上都能正常运行的代码是件好事。
猜你喜欢
  • 2019-05-15
  • 1970-01-01
  • 2020-03-20
  • 2020-11-27
  • 1970-01-01
  • 1970-01-01
  • 2016-02-25
  • 2023-01-14
  • 2017-10-30
相关资源
最近更新 更多