Reputation: 119
Hi I am trying to write a simple program that calculates the base content of each base in DNA. I keep getting an assignment error 'no_c referenced before assignment' or 'no_c not defined" in my current configuration and I can't figure out how to solve the issue.
#!/usr/bin/python
#computing the atgc content of a DNA string
class Base_counter(object):
def __init__(self, DNA):
self.DNA = DNA
no_c = 0
no_a = 0
no_g= 0
no_t= 0
def c_counter(self):
for base in self.DNA:
if base == 'c':
no_c = no_c + 1
return no_c
def g_counter(self):
for base in self.DNA:
if base == 'g':
no_g+=1
return no_g
def a_counter(self):
for base in self.DNA:
if base == 'a':
no_a+=1
return no_a
def t_counter(self):
for base in self.DNA:
if base == 't':
no_a+=1
return no_t
def gc_percentage(self):
return no_c + no_g / len(self.DNA)
def at_percentage(self):
return no_a + no_t / len(self.DNA)
def g_percentage(self):
return no_g / len(self.DNA)
def a_percentage(self):
return no_a / len(self.DNA)
def t_percentage(self):
return no_t / len(self.DNA)
def c_percentage(self):
return no_c / len(self.DNA)
def main():
dna= 'gcgctat'
analyzer = Base_counter(dna)
print analyzer.no_c
print analyzer.c_counter()
#print analyzer.c_percentage()
if __name__ == '__main__':
main()
Upvotes: 1
Views: 82
Reputation: 28370
Just put self.
before all of the no_
values in the class to make them members of each class instance object.
Thus:
class Base_counter(object):
def __init__(self, DNA):
self.DNA = DNA
self.no_c = 0
self.no_a = 0
self.no_g= 0
self.no_t= 0
def c_counter(self):
for base in self.DNA:
if base == 'c':
self.no_c += 1
return self.no_c
etc.
This is needed so that the instance of a specific class has it's own storage for the values and can reference it.
Upvotes: 0
Reputation: 3409
try this:
def c_counter(self):
for base in self.DNA:
if base == 'c':
self.no_c = self.no_c + 1
return self.no_c
Specifically, access all fields of the object with the self keyword.
Upvotes: 0
Reputation: 76297
Consider your code
def __init__(self, DNA):
self.DNA = DNA
no_c = 0
no_a = 0
no_g= 0
no_t= 0
Only the line
self.DNA = DNA
creates a member for this object. The other lines create mappings that are local to this function. Consequently, when later calls try to access no_c
, the interpreter does not connect it to what you presumably meant here.
I'm guessing that you want to replace every occurrence of no_c
with self.no_c
.
Upvotes: 2