Hi,

I wrote below 2 classes to explore how __getitem__(self,k) works in conjuection with list subscriptions. Both code works. Now my questions which way the community encourages more in Python: if isinstance(key, slice): or if type(key) == slice: ? How should I implement this if I follow duck typing, because none of the code currently I wrote using duck typing techiniqe IMO.

class MyCustomList:
    def __init__(self, list = []):
        self.list = list

    def __getitem__(self, key):
        if isinstance(key, slice):
            return self.list[key]
        else:
            return self.list[key]

class MyCustomListV1:
    def __init__(self, list = []):
        self.list = list

    def __getitem__(self, key):
        if type(key) == slice:
            return self.list[key]
        else:
            return self.list[key]

if __name__ == '__main__':
    list = MyCustomList(list=[1, 2, 3, 4, 5, 6])
    print(list[1:3])
    print(list[3])
    print("=======\n")
    list = MyCustomListV1(list=[1, 2, 3, 4, 5, 6])
    print(list[1:3])
    print(list[3])

If run it, I get the output:

[2, 3]
4
=======

[2, 3]
4

--
Thanks,

Arup Rakshit

_______________________________________________
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
https://mail.python.org/mailman/listinfo/tutor

Reply via email to