将元组作为列表继承

Laz*_*h13 4 python tuples list

我只是在编写一个程序,其中有一个继承自a的类tuple.但是,当我将参数作为列表传递时,它仍然有效.这是我的一些代码:

class Board(tuple):    
    def __init__(self, tup):
        print(type(tup))
        super().__init__()

board = Board([[Cell(False) for i in range(10)] for j in range(10)])
print(type(board))
Run Code Online (Sandbox Code Playgroud)

然后该程序输出:

<class 'list'>
<class '__main__.Board'>
Run Code Online (Sandbox Code Playgroud)

我的问题如下:为什么list当我说我会通过时,Python让我传递一个参数作为参数tuple

the*_*eye 5

def __init__(self, tup):
Run Code Online (Sandbox Code Playgroud)

就像其他功能一样.并且您已经传递了tup参数列表.你无法在python中限制参数的类型.子类化tuple只是意味着您从中继承属性tuple,而不是只接受元组作为参数.

编辑:如果您非常想要一种确保只接受元组的方法,出于某种原因.你可以像这样引发异常

class Board(tuple):
    def __init__(self, tup):
        if not isinstance(tup, tuple):
            raise TypeError("Constrcutor argument to Board should be a tuple")
        super().__init__()

print Board([1, 2])
Run Code Online (Sandbox Code Playgroud)

产量

TypeError: Constrcutor argument to Board should be a tuple
Run Code Online (Sandbox Code Playgroud)

性能比较tuplelist

class Board(tuple):
    def __init__(self, tup):
        for i in tup:
            pass
myList, myTuple = range(10), tuple(xrange(10))

from timeit import timeit
print timeit("Board(myList)", "from __main__ import myList, Board", number = 1000000)
print timeit("Board(myTuple)", "from __main__ import myTuple, Board", number = 1000000)
Run Code Online (Sandbox Code Playgroud)

产量

0.44806599617
0.413192987442
Run Code Online (Sandbox Code Playgroud)

这清楚地表明,list作为一个参数传递一个非常慢tuple,几乎可以忽略不计,它们的性能几乎相同.