12.2. Defining operators for classes

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:

  • __add__ to concatenate sub-sequences by the + operator
  • __len__ for computing the length
  • __getitem__ for indexed access to a position in the sequence, etc....
  • __getslice__ for ranges in the sequence
  • etc...

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))
	    

Exercise 12.4. Code reading: Bio.GenBank.Dictionary class

Look at the source code of class Bio.GenBank.Dictionary in order to understand how the following code works:

from Bio import GenBank
gb_dict = GenBank.NCBIDictionary()
gb_rec = gb_dict['1617401']                                               (1)
print gb_rec
	  
1

What happens here?