从namedtuple基类继承-Python [英] Inheriting from a namedtuple base class - Python

查看:98
本文介绍了从namedtuple基类继承-Python的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这个问题与的反义在python 中,其目的是从namedtuple继承子类,反之亦然.

This question is asking the opposite of Inherit namedtuple from a base class in python , where the aim is to inherit a subclass from a namedtuple and not vice versa.

在正常继承中,这可行:

In normal inheritance, this works:

class Y(object):
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c


class Z(Y):
    def __init__(self, a, b, c, d):
        super(Z, self).__init__(a, b, c)
        self.d = d

[输出]:

>>> Z(1,2,3,4)
<__main__.Z object at 0x10fcad950>

但是如果基类是namedtuple:

from collections import namedtuple

X = namedtuple('X', 'a b c')

class Z(X):
    def __init__(self, a, b, c, d):
        super(Z, self).__init__(a, b, c)
        self.d = d

[输出]:

>>> Z(1,2,3,4)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: __new__() takes exactly 4 arguments (5 given)

问题,是否可以在Python中继承namedtuples作为基类?是这样吗?

推荐答案

可以,但必须覆盖__new__,该__new____init__之前隐式调用:

You can, but you have to override __new__ which is called implicitly before __init__:

class Z(X):
  def __new__(cls, a, b, c, d):
    self = super(Z, cls).__new__(cls, a, b, c)
    self.d = d
    return self

>>> z = Z(1, 2, 3, 4)
>>> z
Z(a=1, b=2, c=3)
>>> z.d
4

但是d只是一个独立的属性!

But d will be just an independent attribute!

>>> list(z)
[1, 2, 3]

这篇关于从namedtuple基类继承-Python的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆