50 likes | 64 Views
Learn how to define and utilize classes in Python, including initializing instances, declaring variables and methods, and using attribute notation. Explore a real-world example of generating random DNA sequences based on a probability distribution.
E N D
Capital letters OK Python focus – classes Defining a class Like functions, minimally, all we need is a statement block of Perl code that we have given a name! class I_dont_do_much (object): #any code you like!! pass …but it won’t do anything interesting though until we have specified some data and some methods! Python classes are essentially user-defined data types. We can store data and the methods that work on that data in the same place!
First argument always self Variables prepended with self become instance variables, and are visible throughout the namespace of a class instance Methods defined as functions Python focus – classes The __init__ method This method corresponds to the “constructor” in other OOP languages. It initializes each instance of a class class Gene(object): def __init__(self, sequence, annotation): self.seq = sequence self.annot = annotation Variables declared outside of a method have the same value in all instances of that class!
First argument always self User methods defined as functions Python focus – classes User-defined methods These are the interface with your class class Gene(object): def __init__(self, sequence, annotation): self.seq = sequence self.annot = annotation def test (self, sequence): # depending if seq is in self.seq # return True or False return sequence in self.seq Variable some_var is visible only within the user defined test method!
Instantiate a class by invoking its name, and providing the arguments the __init__ method expects Python focus – classes Using classes my_gene = Gene("AGCTAAAATTG", annotation) my_gene2 = Gene(sequence2, annotation2) result = my_gene.test("AGCT") print result We can make as many instances of a class as we need! We invoke class methods just by using the instance identifier in conjunction with the method name using attribute notation!
Putting it all together - An in-class challenge Get Python up and running, try “Hello world!” then… Write a program that: Defines a function that generates random DNA sequences of some specified length given a dict describing the probability distribution of A, C, G, T You’ll need the rand function from the math library!! This is a real-world chore that is frequently encountered in bioinformatics