python __getitem__ 例

1328 ワード

class Test:
   def __init__(self, id):
     self.id = id

   def __getitem__(self, key):
     out = {
            'src': key,
            'src_len': len(key),
            'tgt': key+'1',
            'tgt_len': len(key) if key else 0
        }
     return out

data = Test(1)
print(data['1'])
print(data.id)
print(data['1']['src'])
print(type(data['1']['src']))