python class behaves like dictionary-or-list-data-like -


in python3 console, input those:

>>> import sys >>> sys.version_info sys.version_info(major=3, minor=4, micro=3, releaselevel='final', serial=0) >>> type(sys.version_info)  # class type <class 'sys.version_info'> >>> sys.version_info[0:2]  # ?? acts list-data-like (3, 4) 

my questions are:

  1. how can class act dictionary-or-list-data-like?
  2. may give example construct class this?
  3. is there documentation this?

python contains several methods emulating container types such dictionaries , lists.

in particular, consider following class:

 class mydict(object):      def __getitem__(self, key):           # called getting obj[key]       def __setitem__(self, key, value):           # called setting obj[key] = value 

if write

obj = mydict() 

then

obj[3] 

will call first method, and

obj[3] = 'foo' 

will call second method.

if further want support

len(obj) 

then need add method

def __len__(self):     # return here logical length 

here example of (very inefficient) dictionary implemented list

class mydict(object):     def __init__(self, seq=none):         self._vals = list(seq) if seq not none else []      def __getitem__(self, key):         return [v[1] v in self._vals if v[0] == key][0]      def __setitem__(self, key, val):         self._vals = [v v in self._vals if v[0] != key]         self._vals.append((key, val))      def __len__(self):         return len(self._vals) 

you can use pretty regular dict:

obj = mydict() obj[2] = 'b' >>> obj[2] 'b' 

Comments