Intermediate classes
| Previous: Beginning classes | Next: Beginning unit test |
Required course material for the lesson
Powerpoint: Classes
Resource: Example code - Classes
Subjects covered
Magic methods in classes
Object Oriented Programming
Polymorphism and inheritance
Practical knowledge
Exercises to be handed in
The first two exercises will continue with the Fasta class from last time.
- Use magic methods to add iteration and length evaluation (using __iter__ and __len__ magic methods) to the Fasta class. Do this so you can write code like if len(MyFastaInstance) > 0:The function len returns the number of sequences.
for header, sequence in MyFastaInstance:
# Do something with header and sequence
print(header, sequence) - Add the methods deletethis(), insertthis(header, sequence), verifythis(alphabet) and discardthis(alphabet) to the Fasta class. The methods should only work when iterating over an instance at the current item, i.e. they work when you are iterating over the fasta sequences on the current sequence and header, like this:for header, sequence in MyFastaInstance:As some may remember, it is normally impossible to successfully iterate straightforward through a list and delete and/or add elements to the list during the iteration. You have to make this possible. Hint: change the way your iteration works in the previous exercise.
if not MyFastaInstance.verifythis("DNA"):
MyFastaInstance.deletethis()
continue
# Do something with header and sequence - Let's do something natural. Make it possible to add one FastaInstance to another using the += operator, like this:FastaInstance1 += FastaInstance2The headers and sequences in Fastainstance2 should be added (list extension) to the headers and sequences in FastaInstance1. Use the magic method __iadd__.
- Implement the addition, using __add__. Addition creates a new Fasta instance, but leaves the originals untouched.FastaInstance3 = FastaInstance1 + FastaInstance2The resulting Fasta object must contain the headers and sequences from FastaInstance1 and FastaInstance2 in that order. Note that this works as an alternative constructor.