Standard methods enable to define the behaviour of standard operators:
Example 12.2. Seq operators
For instance, the Seq class defines a method __str__ which returns a string informally representing the sequence, that will be used in print statement, as well as several other operators:
class Seq:
def __repr__(self):
return "%s(%s, %s)" % (self.__class__.__name__,
repr(self.data),
repr(self.alphabet))
def __str__(self):
if len(self.data) > 60:
s = repr(self.data[:60] + " ...")
else:
s = repr(self.data)
return "%s(%s, %s)" % (self.__class__.__name__, s,
repr(self.alphabet))
def __len__(self): return len(self.data)
def __getitem__(self, i): return self.data[i]
def __getslice__(self, i, j):
i = max(i, 0); j = max(j, 0)
return Seq(self.data[i:j], self.alphabet)
def __add__(self, other):
if type(other) == type(' '):
return self.__class__(self.data + other, self.alphabet)
elif self.alphabet.contains(other.alphabet):
return self.__class__(self.data + other.data, self.alphabet)
elif other.alphabet.contains(self.alphabet):
return self.__class__(self.data + other.data, other.alphabet)
else:
raise TypeError, ("incompatable alphabets", str(self.alphabet),
str(other.alphabet))