【问题标题】:Python inheritance from lists [duplicate]Python从列表继承[重复]
【发布时间】:2016-05-03 18:55:41
【问题描述】:

我刚开始学习 Python,并创建了以下继承自列表的类:

class Person(list):
    def __init__(self, a_name, a_dob=None, a_books=[]):
        #person initialization code
        list.__init__(a_books)
        self.name = a_name
        self.dob = a_dob

但是,有三件事我不明白:

  1. list.__init__(a_books) 这一行实际上并未初始化我的实例的图书列表。
  2. 根据这本书,我应该改写list.__init__([])。为什么需要这一步。
  3. 为什么list.__init__([]) 中没有对self 的引用? Python 是怎么知道的?

【问题讨论】:

  • 对于一个实用的系统,您可能希望 list 成为 Person 的一个属性,而不是从 list 继承。

标签: python inheritance


【解决方案1】:

你需要创建一个super call to instantiate the object using the parents __init__ method first:

class Person(list):
    def __init__(self, a_name, a_dob=None, a_books=[]):
        #person initialization code
        super(Person, self).__init__(a_books)
        self.name = a_name
        self.dob = a_dob

print Person('bob',a_books=['how to bob'])

Gives the output:

['how to bob']

因为list 有一个__str__ 方法。

【讨论】:

    猜你喜欢
    • 2019-05-02
    • 2020-04-28
    • 2015-05-24
    • 2020-03-16
    • 2020-11-04
    • 1970-01-01
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    相关资源
    最近更新 更多