继承方法内置类型

时间:2014-03-12 07:42:23

标签: python

class Mylist(list):pass
y = Mylist('abc')
y
['a', 'b', 'c']
y.__dict__
{}

Mylist类继承自内置类型列表。为什么在输出实例y时显示列表(对象y为空)?

2 个答案:

答案 0 :(得分:1)

列表对象没有__dict__

>>> l = []
>>> l.__dict__
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'list' object has no attribute '__dict__'

列表数据存储在存储对象的C结构的某个字段中。从list继承时,您将获得__dict__属性,但列表数据仍存储在C属性中。这就是你不能看到它们的原因。这是列表类型的C源代码(Python 2.7.2):

typedef struct {
    PyObject_VAR_HEAD
    /* Vector of pointers to list elements.  list[0] is ob_item[0], etc. */
    PyObject **ob_item;

    /* ob_item contains space for 'allocated' elements.  The number
     * currently in use is ob_size.
     * Invariants:
     *     0 <= ob_size <= allocated
     *     len(list) == ob_size
     *     ob_item == NULL implies ob_size == allocated == 0
     * list.sort() temporarily sets allocated to -1 to detect mutations.
     *
     * Items must normally not be NULL, except during construction when
     * the list is not yet visible outside the function that builds it.
     */
    Py_ssize_t allocated;
} PyListObject;

对象存储在ob_item数组中,其分配的大小为allocated

答案 1 :(得分:0)

y继承list构造函数,该构造函数使用'abc'的元素并使它们成为y的元素。字典空的事实意味着很少;列表的元素不存储在其字典中。