How would I create a custom list class in python?

后端 未结 5 1383
一个人的身影
一个人的身影 2020-12-14 16:25

I would like to write a custom list class in Python (let\'s call it MyCollection) where I can eventually call:

for x in myCollectionInstance:
           


        
5条回答
  •  爱一瞬间的悲伤
    2020-12-14 16:37

    You could extend the list class:

    class MyList(list):
    
        def __init__(self, *args):
            super(MyList, self).__init__(args[0])
            # Do something with the other args (and potentially kwars)
    

    Example usage:

    a = MyList((1,2,3), 35, 22)
    print(a)
    for x in a:
        print(x)
    

    Expected output:

    [1, 2, 3]
    1
    2
    3
    

提交回复
热议问题