Overload item getter operator

Overload __getitem__

__getitem__(self, key) returns the value corresponding to the given key. For a sequence, the key should be an integer from zero to n-1 or, it could be negative, where n is the length of the sequence.

For a mapping, you could really have any kind of keys. For a sequence, if the key is a negative integer, it should be used to count from the end. In other words, treat x[-n] the same as x[len(x)-n].


class MyList:# www.  ja  v a  2  s . c o m
    def __init__(self, start):
        self.wrapped = []                        # Make sure it's a list here.
        for x in start: self.wrapped.append(x)
    def __add__(self, other):
        return MyList(self.wrapped + other)
    def __mul__(self, time):
        return MyList(self.wrapped * time)
    def __getitem__(self, offset):
        return self.wrapped[offset]
    def __len__(self):
        return len(self.wrapped)
    def __getslice__(self, low, high):
        return MyList(self.wrapped[low:high])
    def append(self, node):
        self.wrapped.append(node)
    def __getattr__(self, name):                 # Other members: sort/reverse/etc
        return getattr(self.wrapped, name)
    def __repr__(self):
        return self.wrapped

x = MyList('spam')
print x
print x[0]
print x[1:]
print x + ['eggs']
print x * 3
x.append('a')
x.sort( )
for c in x: print c,

The code above generates the following result.





















Home »
  Python »
    Language Basics »




Python Basics
Operator
Statements
Function Definition
Class
Buildin Functions
Buildin Modules