为什么我的Python继承/超级示例不起作用?

2024-09-28 22:24:42 发布

您现在位置:Python中文网/ 问答频道 /正文

为什么以下方法不起作用:

class CTest(tuple):
    def __init__(self,arg):
        if type(arg) is tuple:
            super(CTest,self).__init__((2,2))
        else:
            super(CTest,self).__init__(arg)
a=CTest((1,1))
print a

输出是(1,1),而我期望看到(2,2)。在

另外,为什么我会收到一个不推荐使用的警告:object.init()不带参数?我该怎么办?在


Tags: 方法selfifinitisdeftypearg
1条回答
网友
1楼 · 发布于 2024-09-28 22:24:42

元组是不可变的,您必须重写__new__

class CTest(tuple):
    def __new__(cls, arg):
        if type(arg) is tuple:
            return super(CTest, cls).__new__(cls, (2, 2))
        else:
            return super(CTest, cls).__new__(cls, arg)

现在这一切如期而至:

^{pr2}$

请看这个post以了解更多详细信息。在

相关问题 更多 >