为什么这样的类装饰器只能处理list的子类,而不能处理tuple的子类

时间:2019-01-05 17:48:56

标签: python decorator

尽管这可以创建仅将整数作为项目的list子类(简化版本,仅具有构造函数重载),但它不包含元组。装饰的类是元组的子类时,super().__init__是否应该调用tuple.__init__

#!/usr/bin/env python3

def only(thetype):
    def __(cls):
        class _(cls):
            def __init__(self,iterable):
                super().__init__( [ thetype(x) for x in iterable ] )
        return _
    return __

@only(int)
class myList(list):
    pass

l = myList( [1,2,3,3.14,"42"] )
print(l) # [1, 2, 3, 3, 42 ]

@only(int)
class myTuple(tuple):
    pass

t = myTuple( [1,2,3,3.14, "42"] )
# TypeError: object.__init__() takes no arguments
print(t)

0 个答案:

没有答案