Inheritance of a tuple as a list

I just wrote a program that has a class that inherits from tuple. However, when I passed the argument as a list, it still worked. Here is my code:

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))

Then this program displays:

<class 'list'>
<class '__main__.Board'>

My question is this: why did Python let me pass listas an argument when I said that I would pass tuple?

+4
source share
6 answers
def __init__(self, tup):

. 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])

TypeError: Constrcutor argument to Board should be a tuple

tuple list

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)

0.44806599617
0.413192987442

, a list , tuple, , .

+5

, , tup . , Python . :

if type(tup) is not type(()):
    raise ValueError('Expected a tuple')

. Pythonic - , , , , .

+1

tuple , , .

; . , , .

+1

.

, :

class Board(tuple):    
    def __init__(self, tup):
        print(type(tup))
        d={}
        d[tup]='test'          # this will fail with an unhashable type, like a list
        super().__init__()

b1=Board(tuple([1,2,3]))
b2=Board([1,2,3])

<class 'tuple'>
<class 'list'>
Traceback (most recent call last):
  File "Untitled 8.py", line 9, in <module>
    b2=Board([1,2,3])
  File "Untitled 8.py", line 5, in __init__
    d[tup]='test'
TypeError: unhashable type: 'list'

Python . EAFP .

"" , collections.abc.

0

tuple __init__, :

class Board(tuple):    
    def __init__(self, tup):
        if not isinstance(tup, tuple):
            raise Exception('Invalid type')
        super().__init__()

. .

0

.

>>> tuple([1,2,3])  # tuple() takes a list
(1, 2, 3)           # turns it into a tuple

tuple tuple; , tuple.

-1

All Articles