soarinblue soarinblue - 1 year ago 82
Python Question

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) # this is class type
<class 'sys.version_info'>
>>> sys.version_info[0:2] # ?? But it acts like a list-data-like
(3, 4)

My questions are:

  1. How can a class act like dictionary-or-list-data-like?

  2. May give an example to construct a class like this?

  3. Is there some documentation about

Answer Source

Python contains several methods for emulating container types such as dictionaries and lists.

In particular, consider the following class:

 class MyDict(object):
     def __getitem__(self, key):
          # Called for getting obj[key]

     def __setitem__(self, key, value):
          # Called for setting obj[key] = value

If you write

obj = MyDict()



will call the first method, and

obj[3] = 'foo'

will call the second method.

If you further want to support


then you just need to add the method

def __len__(self):
    # Return here the logical length

Here is an example of a (very inefficient) dictionary implemented by a list

class MyDict(object):
    def __init__(self, seq=None):
        self._vals = list(seq) if seq is not None else []

    def __getitem__(self, key):
        return [v[1] for v in self._vals if v[0] == key][0]

    def __setitem__(self, key, val):
        self._vals = [v for v in self._vals if v[0] != key]
        self._vals.append((key, val))

    def __len__(self):
        return len(self._vals)

You can use it pretty much like a regular dict:

obj = MyDict()
obj[2] = 'b'
>>> obj[2]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download