python3 中object.__init__() takes no parameters 报错问题

初学python

代码如下:

class IntTuple(tuple):


def __new__(cls, iterable):
    g = (x for x in iterable if isinstance(x,int) and x > 0)
    return super(IntTuple, cls).__new__(cls, g)


def __init__(self, iterable):
    super(IntTuple, self).__init__(iterable)

    

t = IntTuple([1,-1,'abc',6,['x','y'],3])
print(t)

为什么在不实现__init__方法时无报错,而以上代码会出现错误?
忘解答

阅读 3.2k
1 个回答
import inspect
class IntTuple(tuple):
    def __new__(cls, iterable):
        g = (x for x in iterable if isinstance(x,int) and x > 0)
        return super(IntTuple, cls).__new__(cls, g)
    def __init__(self, iterable):
        print(inspect.getargspec(super(IntTuple, self).__init__))    # 打印父类的__init__ 
        # ArgSpec(args=['self'], varargs='args', keywords='kwargs', defaults=None)
        print(iterable)

t = IntTuple([1,-1,'abc',6,['x','y'],3])
print(inspect.getargspec(t.__init__))    # 打印你自己定义的__init__
# ArgSpec(args=['self', 'iterable'], varargs=None, keywords=None, defaults=None)

你会发现tuple父类的__init__根本没有参数传递,从报的错误可以看出,tuple没有实现__init__魔术方法,而是直接继承的object。从传递的参数也可以看出来,iterable还是那个没处理的,而不是从__new__里传递过来的g

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题