Create a directory `my_first_class` and launch Spyder or your favourite IDE.
Write a class `DNA` in a file `dna.py`. In the same folder my_first_class, create another file `test_dna.py` which has following lines.
# File test_dna.py
#
from . import dna
myDNA = dna.DNA("GATGATCGATGAGAGTGATGAAGAAAA")
if myDNA.sane():
myDNA.getCodons()
else:
print("This DNA look fishy")
The `import` line says that "from directory . (current directory) import dna". For this line to be successful, you must have a file called `dna.py` in the same directory.
Second line creates an object of class DNA called myDNA. Notice what happens when you replace `dna.DNA` with `DNA` only?
Also recall that when we construct an object, default constructor (function named `__init__`) is always called. This time this function is called with one argument: `dna.DNA("GAT....")` instead of `dna.DNA()`.
Further we check whether `myDNA` is `sane` or not. What sort of tests I should run on my sequence (string)? Once you have written them down, we can think of translating them to algorithms e.g. if I only want to test that every character in my sequence is either A, G, C, or T. All I need to do is to write a for loop, and test for membership. Psuedo-code: for every i in self.sequence: check if i belongs to set(A, G, C, T).
Why not write a small function to do that first?
Function `sane()` must return something which make sense to `if`: usually bool. Our next four lines are saying (assuming that function `sane` returns True of False): "if myDNA is sane then get me all the codons else tell the user that this DNA look fishy and exit".
Now I can write the template of the class now.
#File dna.py . It must be in the same directory where test_dna.py reside.
class DNA():
"""My class DNA """
def __init__(self, sequence):
self.sequence = sequence
self.codons = set()
def sane(self):
"""Check if given sequence is sane or not. Return True of False"""
print("Testing sanity of given sequence %s " % self.sequence)
def codons(self):
"""This function computes the codons. And prepare a 'set' of them
Why set and not list?
I don't want to keep duplicates. Do I?
"""
pass
The code above may not be indented correctly. Instead of copy-pasting, do write fresh in Spyder.
How to share your code when you need help?There are many ways but we would like you to use
http://github.com for all the code you write for this forum. Create an account on github. Whenever you code is not working, copy and paste it on
https://gist.github.com and share the link here with the problem you faced.
Github (and
stackoverflow.com) is where programmers go social (to be more productive). On github, we can easily edit, pass comments and fix your code without loosing any history. (You can also use git/svn with github for version control but let's not worry about it now. Wait for Cosmic Owl to tell us about this Wildly Significant Thing (WST) someday.)
Dilawar
EDIT: This post is edited to fix grammar and to make it more readable.