Create a python object that can be accessed with square brackets

后端 未结 2 1735
终归单人心
终归单人心 2020-12-29 01:28

I would like to create a new class that acts as a special type of container for objects, and can be accessed using square brackets.

For example, suppose I have a cla

2条回答
  •  长发绾君心
    2020-12-29 02:10

    You want to define the special __getitem__[docs] method.

    class Test(object):     
        def __getitem__(self, arg):
            return str(arg)*3
    
    test = Test()
    
    print test[0]
    print test['kitten']
    

    Result:

    000
    kittenkittenkitten
    

提交回复
热议问题