python - 使用 str 为 init 子类化元组

标签 python inheritance constructor tuples subclass

我正在尝试创建 tuple 的子类它在各方面的表现都像正常的 tuple异常(exception)的是我使用一个字符串初始化它,该字符串首先由构造函数自动分割(我也希望它的 __str__() 再次加入它,但这不是这里的问题)。

我认为这很简单,并尝试了这样的操作:

class C(tuple):
  def __init__(self, text):
    super(C, self).__init__(text.split(':'))

  def __str__(self):
    return '[%s]' % ':'.join(self)

c = C('one:two:three')  # I expect this to be like ('one', 'two', 'three')

所以我尝试传递 text (a str ),将其拆分并使用结果调用我的父类(super class)的构造函数。我期望得到像 tuple([ 'one', 'two', 'three' ]) 这样的结果, 我。 e.单词元组:('one', 'two', 'three') .

但是我得到了一个字符元组,i。 e.输入'one:two:three'我得到一个('o', 'n', 'e', ':', 't', 'w', 'o', ':', 't', 'h', 'r', 'e', 'e')这正是我调用 tuple('one:two:three') 时得到的结果.

我调试了这种情况,发现我的代码得到了正确执行(我的 __init__() 被调用,并使用正确的值调用另一个 __init__() )。我还尝试更换 super由混凝土 build tuple.__init__(self, text.split(':')) ,但这并没有改变任何事情。我还尝试传递 tuple而不是 list创建者 split() ,也没有变化。其实就是调用super的__init__()似乎没有任何效果。解释器仍然使用我最初传递的字符串来初始化元组。

我错过了什么吗?为什么这没有按预期工作?如何创建一个类 C它是 tuple 的子类我可以通过调用 C('one:two:three') 来初始化它获取 C 的实例这是一个类似 ('one', 'two', 'three') 的元组?

最佳答案

由于元组是不可变的,因此使用 __new__ 而不是 __init__:

class C(tuple):
    def __new__(cls, text):
        return super(C, cls).__new__(cls, text.split(':'))

    def __str__(self):
        return '[%s]' % ':'.join(self)

c = C('one:two:three')
print(c)
print(list(c))

关于python - 使用 str 为 init 子类化元组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42405131/

相关文章:

java - 设计模式处理具有许多成员的类(不是构建器)

java - 继承和可迭代

java - Kotlin : Passing HashMap with multiple value types into function

scala - 是否可以在 Scala 中定义构造函数局部变量?

javascript - 使用 AJAX POST 发布数据

C++ 设计 : cast from base to derived class with no extra data members

python - 元组列表中的列表列表,重新排序

c++ - 为什么 X(X&) 可以调用两次?

python - 我如何知道导入的库来自 python 中的哪个目录?

python - Python轮子名称中的 'cp3xm'和 'cp2xm'是什么意思?