I am trying to define condition to class, if my object Does not meet the conditions:
The conditions: all the organs is vectors, the shape of the vectors is the same.
When I try to casting the object the function will return None.
Thats what I tried so far:
class Matrix:
def __init__(self,m1):
dic_len = {}
self.m1 = tuple(m1)
checking = 0
for i in self.m1:
dic_len[len(i)] = 'check'
if type(i) != Vector:
self.m1 = None
checking = 1
if len(dic_len) != 1:
self.m1 = None
if len(dic_len) == 1 and checking == 0:
self.content = self.m1 = tuple(m1)
self.shape = (len(m1),len(m1[0]))
def __repr__(self):
if self.m1 != None:
return "(" + ", ".join(str(i) for i in self.m1) + ")"
else:
return None
But I get this error:
>>>v1 = Vector([1,2])
>>>v2 = Vector([4,5,6])
>>>m = Matrix([v1,v2])
>>>print(m)
TypeError: __str__ returned non-string (type NoneType)
i wish the function will return None.
return str(None)
instead of
return None
The CPython docs state for the __repr__ method state that
The return value must be a string object.
So returning None isn't going to work.
>>> class C:
... def __repr__(self):
... return None
...
>>> c = C()
>>> repr(c)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: __repr__ returned non-string (type NoneType)
If you're going to share your code with others, it might be better to code __repr__ to produce its coventional output:
...this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment)...
And override __str__ to produce a representation that indicates the validity of the object instance (though note __str__ must also return a string).
I'm trying to create my own list type with a new class called TZList,
I tried to create it with a recursive __init__ func but it won't work,
here's the code:
class TZList:
def __init__(self, *args):
numargs = len(args)
self.value = None
self.next = None
if numargs == 0:
self.value = None
self.next = None
elif numargs == 1:
self.value = args[0]
self.next = None
else:
self.value = args[0]
numargs -= 1
args = args[1:]
self.next = TZList(args)
when i try to get the data like this:
t = TZList(1,2,3)
print(t.value)
print(t.next.value)
print(t.next.next.value)
i get a weird print:
Traceback (most recent call last):
1
(2, 3)
File "C:\****\a3.py", line 79, in <module>
print(t.next.next.value)
AttributeError: 'NoneType' object has no attribute 'value'
and i have no idea why, hope you could help me.
The reason is the way you are repassing args into TZList. You are passing it as a tuple. Instead of self.next = TZList(args) do self.next = TZList(*args)
I am trying to implement a 2-3 tree but I am having trouble with the find method.
This method given an int as parameter should return the node that contains the int.
The problem is that sometimes it works, sometimes it does't and I don't know why.
I have added a test print. For a particular int that I know for sure that is part of the tree, the code executes the print statement, meaning that it has found the node, but does not return this node. Instead it return False which is at the end of the code.
Can you help me solving this ?
def find(self,data,node=0): #return problem ???
if node==0:
a=self.root
else:
a=node
if a.data2==None:
if data==a.data: ### here is the problem
print("qwertyuiop") ### it does not execute the return statement
return a
elif data < a.data:
if a.left!=None:
return self.find(data,a.left)
elif data > a.data:
if a.right!=None:
return self.find(data,a.right)
else:
if a.data2!=None:
if (data==a.data or data==a.data2):
return a
elif data<a.data:
if a.left!=None:
return self.find(data,a.left)
elif (data>a.data and data<a.data2):
if a.middle!=None:
return self.find(data,a.middle)
elif data>a.data2:
if a.right!=None:
return self.find(data,a.right)
print("Not Found") ### function executes this print
return False
self.root is the root of the tree and is an object of the following class
class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.data2 = None
self.data3 = None
self.left = left
self.right = right
self.middle = None
self.middle2 = None
Binary Search Tree:
class Nodeee:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
class BST:
def __init__(self, root=None):
self.c=[]
self.total=0
self.root = None
def parent(self,data,node=5):
def search(nodee,cc,data):
if data==cc.data:
return nodee
else:
if data<cc.data:
nodee=cc
return search(nodee,cc.left,data)
elif data>cc.data:
nodee=cc
return search(nodee,cc.right,data)
print("Parent Error")
return False
if node==self.root:
print("Root has no parent")
else:
a=self.root
c=self.root
return search(a,c,data)
def lookup(self,data,node=0):
if node==0:
a=self.root
else:
a=node
if data < a.data:
if a.left==None:
return a
else:
return self.lookup(data,a.left)
elif data > a.data:
if a.right==None:
return a
else:
return self.lookup(data,a.right)
def find(self,data,node=0):
if node==0:
a=self.root
else:
a=node
if data==a.data:
print("WTF")
return a
elif data < a.data:
if a.left!=None:
return self.find(data,a.left)
elif data > a.data:
if a.right!=None:
return self.find(data,a.right)
print("Not Found")
return False
def find2(self,data,node=0):
if node==0:
a=self.root
else:
a=node
if data==a.data:
return True
elif data < a.data:
return self.find2(data,a.left)
elif data > a.data:
return self.find2(data,a.right)
return False
def is_empty(self):
if self.root==None:
return True
def is_leaf(self,n):
if (n.left==None and n.right==None):
return True
return False
def delete(self):
self.root=None
def insert(self, data):
if self.root==None:
self.root=Nodeee(data)
self.total+=1
return True
else:
b=self.lookup(data)
if data < b.data:
b.left=Nodeee(data)
self.total+=1
return True
elif data > b.data:
b.right=Nodeee(data)
self.total+=1
return True
print("Insert Error !")
return False
def inorder_swap(self,data):
a=self.find(data)
b=a.right
while self.is_leaf(b)!=True:
if b.left!=None:
b=b.left
elif b.left==None:
b=b.right
temp=a.data
a.data=b.data
b.data=temp
def remove(self,data):
a=self.find(data)
if self.is_leaf(a)==True:
b=self.parent(data)
if b.left==a:
b.left=None
elif b.right==a:
b.right=None
elif self.is_leaf(a)==False:
if a.left==None:
b=self.parent(data)
if b.left==a:
b.left=b.left.right
elif b.right==a:
b.right=b.right.right
elif a.right==None:
b=self.parent(data)
if b.left==a:
b.left=b.left.left
elif b.right==a:
b.right=b.right.left
elif (a.left!=None and a.right!=None):
self.inorder_swap(data)
self.remove(data)
def inorder(self,node):
if node!=None:
self.inorder(node.left)
self.c.append(node.data)
self.inorder(node.right)
def inorder_print(self):
self.c=[]
self.inorder(self.root)
print("\nStart")
for x in range(len(self.c)):
print(self.c[x], end=",")
print("\nFinish\n")
a=BST()
print(a.insert(234)==True)
print(a.insert(13)==True)
print(a.insert(65)==True)
print(a.insert(658)==True)
print(a.insert(324)==True)
print(a.insert(86)==True)
print(a.insert(5)==True)
print(a.insert(76)==True)
print(a.insert(144)==True)
print(a.insert(546)==True)
print(a.insert(2344)==True)
print(a.insert(1213)==True)
print(a.insert(6345)==True)
print(a.insert(653348)==True)
print(a.insert(35324)==True)
print(a.insert(8463)==True)
print(a.insert(5555)==True)
print(a.insert(76539)==True)
print(a.insert(14499)==True)
print(a.insert(59999946)==True)
a.inorder_print()
a.remove(35324)
a.remove(1213)
a.remove(2344)
a.remove(144)
a.remove(5555)
a.remove(6345)
a.remove(59999946)
a.remove(76)
print(a.root.data)
a.inorder_print()
def inorder_swap(self,data):
a=self.find(data)
b=a.right
while self.is_leaf(b)!=True:
if b.left!=None:
b=b.left
elif b.left==None:
b=b.right
temp=a.data
a.data=b.data
b.data=temp
a here is the node containing the passed data. This method does nothing else than swapping a's data with some leaf's data (first one while finds), thereby distorting the tree order. A follow-up find on the same data therefore fails and returns False. Since your code has no error checks, this results in an AttributeError.
You probably want to move nodes around in inorder_swap. However you only assign to the local name b. If you want to change nodes, then you need to use b.left = or b.right =.
It might be that there are more problems, that I don't see right now.
Also your code has several style problems, some of them:
You have four functions doing the same: find, find2, lookup and search in parent.
Most of the naming is not informative or even confusing.
Lines like if a.right==None: should be written as if not a.right: (or maybe if a.right is None:).
Check the return value of functions and don't just assume they return a valid node if they might not (i.e. find might return False instead of a node). Or alternatively use exception handling.
If you have an if ... elif ... elif block you don't have to check the last possibility if it is sure to be true, for example:
if b.left!=None:
# something
elif b.left==None:
# something else
should be
if b.left:
# something
else:
# something else
i am a newbie on this site and am also a newbie to programming, i'm trying to learn python using a book for beginners on python 3.1. I have come across an example that just won't work whatever I try, I have searched for faults in writing about 10 times still it seems exactly what I see in the book. This is the example:
the fridge class
#!/usr/bin/env
class Fridge:
"""methods:
has(food_name [, quantity])-chk if string is in the fridge
has_various(foods)-chk if enough food is in the fridge
add_one(food_name) -adds 1 food
add_many(food_dict)- adds dict to fridge
get_one(food_name)- take out 1 food
get_many(food_dict) - a dict out of fridge
get_ingred(food)- if passed an obj get the list of __ingredients__
"""
def __init__(self, items={}) :
if type(items) != type({}):
raise typeError("Fridge req a dict but was given %s" % type(items))
self.items=items
return
def __add_multi(self, food_name, quantity):
if (not food_name in self.items):
self.items[food_name]=0
self.items[food_name]=self.items[food_name]+quantity
def add_one(self, food_name):
if type(food_name) != type(""):
raise TypeError ("add_one requires a string givem a %s " % type(food_name))
else:
self.__add_multi(food_name, 1)
return True
def add_many(self, food_dict):
if type(food_dict) != type({}):
raise TypeError ("add_many requires a dict, got a %s" % type(food_dict))
for item in food_dict.keys() :
self.__add_multi(item, food_dict[item])
return
def has(self, food_name, quantity=1):
return self.has_varoius({food_name:quantity})
def has_various(self, foods):
try:
for food in foods.keys():
if self.items[food] < foods[food]:
return False
return True
except KeyError:
return Fasle
def __get_multi(self, food_name, quantity):
try:
if (self.items[food_name] is None) :
return False
if (quantity > self.items[food_name]):
return False
self.items[food_name] = self.items[food_name] - quantity
except KeyError:
return False
return quantity
def get_one(self, food_name):
if type(food_name) !=type(""):
raise TypeError("get_one requires a string and was given a %s" % type(food_name))
else:
result=self.__get_multi(food_name, 1)
return result
def get_many(self, food_dict):
if self.has_various(food_dict):
foods_removed={}
for item in food_dict.keys():
foods_removed[item]=self.__get_multi(item, food_dict[item])
return foods_removed
def get_ingredients(self, food):
try:
ingredients=self.get_many(food.__ingredients())
except AttributeError:
return False
if ingredients!=False:
return ingredients
the omelet class
#!/usr/bin/env python3.3
class Omelet:
def __init__(self, kind="cheese"):
self.set_kind(kind)
return
def __ingredients__(self):
return self.needed_ingredients
def get_kind(self):
return self.kind
def set_kind(self, kind):
possible_ingredients=self.__known_kinds(kind)
if possible_ingredients == False :
return False
else:
self.kind=kind
self.needed_ingredients= possible_ingredients
def set_new_kind(self, name, ingredients):
self.kind=name
self.needed_ingredients= ingredients
return
def __known_kinds(self, kind):
if kind == "cheese":
return {"eggs":2, "milk":1, "cheese":1}
elif kind == "mushroom":
return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
elif kind == "onion":
return {"eggs":2, "milk":1, "cheese":1, "onion":1}
else:
return False
def get_ingredients(self, fridge):
self.from_fridge= fridge.get_ingredients(self)
def mix(self):
for ingredient in self.from_fridge.keys():
print("mixing %d %s for the %s omelet" % (self.from_fridge["ingredient"], ingredient, self.kind))
self.mixed=True
def make(self):
if self.mixed == True:
print("Cooking the %s omelet!" % self.kind)
self.cooked = True
this is how i invoke the classes and what i do to use the classes and the error i get
>>> exec(open("/home/knoppix/test/fridge.py").read())
>>> exec(open("/home/knoppix/test/omelet.py").read())
>>> o=Omelet("cheese")
>>> f=Fridge({"cheese":5, "milk":4, "eggs":12})
>>> o.get_ingredients(f)
>>> o.mix()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 41, in mix
AttributeError: 'bool' object has no attribute 'keys'
Please excuse me if there is a typing fault in the code , it`s exactly what I found in the book!
def get_ingredients(self, fridge):
self.from_fridge= fridge.get_ingredients(self)
In this function, your fridge.get_ingredients() might be returning False.
So self.from_fridge has Boolean value which does not have keys() method.
You may want to add appropriate check in mix() method.
The function "__known_kinds(kind)" should preferably return {} to be consistent, instead of different object types although "None" is better than "False".
if kind == "cheese":
return {"eggs":2, "milk":1, "cheese":1}
elif kind == "mushroom":
return {"eggs":2, "milk":1, "cheese":1, "mushroom":2}
elif kind == "onion":
return {"eggs":2, "milk":1, "cheese":1, "onion":1}
else:
return {}
Then you only have to deal with dictionary type in mix() method. The else can also be dropped from mix() as exception will be raised if dict == {}.
def mix(self):
if self.from_fridge == {}:
raise IndexError("self.from_fridge returns Nothing")
for ingredient in self.from_fridge.keys():
....
I have this python file that I'm working on:
class Range:
""" An object that has a non-negative start position and a non-negative length"""
def __init__(self, start, end):
"""
Function: generates a new Range
Returns : a new range
Args : start - start position
end - end position
Start and End must be non-negative """
self.start = 0
self.end = 10000
self.setStart(start)
self.setEnd(end)
def getStart(self):
"""
Function: get the start of the range
Returns : a number or None
Args : start - the int index of the first nucleotide of this range """
return self.start
def setStart(self, s):
"""
Function: set the start of the range
Returns : None
Args : start - a non-negative int or None """
if type(s) !=int:
raise TypeError ("Cannot set Start as this is not an interger")
elif s < 0:
raise ValueError ("Cannot set Start as this is not a non-negative int")
elif s > self.end:
raise ValueError("start cannot be larger than end")
else:
self.start = s
def getEnd(self):
"""
Function: get the end of the range
Returns : a number
Args :
"""
return self.end
def setEnd(self, e):
"""
Function: set the end of the range
Returns : None
Args : end - a non-negative int or None
"""
if type(e) !=int:
raise TypeError ("Cannot set End as this is not an interger")
elif e < 0:
raise ValueError ("Cannot set End as this is not a non-negative int")
elif e < self.start:
raise ValueError ("end has to be larger than start")
else:
self.end = e
def getLength(self):
"""
Function: get the length of the range
Returns : an int. the length of this range
Args:
"""
return self.end - self.start
def overlaps(self, r):
"""
Function: to test if two nucleotide is overlap
Returns : True or False
Args : other - a Range object
"""
start1 = self.getStart()
end1 = start1 + self.getLength()
start2 = r.getStart()
end2 = start2 + self.getLength()
max_start = max(start1,start2)
min_end = min(end1,end2)
return min_end - max_start > 0
if self.getStart() == r.getStart():
return True
else:
return False
class DNAFeature(Range):
"""Represents a feature on a DNA sequence """
def __init__(self, seq_name = None, strand = 0, **kwargs):
"""
Function : represents a rane
Returns :
Args : strand, seqname, **kwargs
"""
Range.__init__(self, **kwargs)
self.setStrand(strand)
self.setSeqName(seq_name)
def getSeqName(self):
"""
Function: Gets object's Sequence Name
Returns : seqname - string
Args :
"""
return self.seq_name
def setSeqName(self, seq_name):
"""
Function: Sets object's Sequence Name
Returns : None
Args : seqname - mRNA accession name
"""
self.seq_name = seq_name
def getStrand(self):
"""
Function: Retrieve the strand affiliation of this
Returns : 1, 0, -1 - strand
Args :
"""
return self.strand
def setStrand(self, strand):
"""
Function: sets which strand the object is on
Returns : None
Args : strand - one of ['+',1,'F','-',-1,'R']
"""
StrandValues = [1, 0, -1]
if not strand in StrandValues:
raise ValueError("only able to setStrand if the values is 1, 0, or -1")
else:
self.strand = strand
def overlaps(self, other, ignore_strand = True):
"""
Function: tests if this overlaps other
Returns : true if the ranges have same Seqname and overlap, false if not
Args : other - another Range object
"""
if ignore_strand == True and self.getSeqName() == other.getSeqName():
return Range.overlaps(self,other)
else:
return False
class GeneModel(DNAFeature):
def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs):
"""
Function : contains a group of DNAFeature objects representing exons
Returns :
Args : **kwargs
"""
DNAFeature.__init__(self, **kwargs)
self.setTranslStart(transl_start)
self.setTranslStop(transl_stop)
self.setDisplayId(display_id)
self.exons = [ ]
def getFeats(self):
"""
Function: gets object's feats list
Returns : list of feature keys
Args : feature_type - the type of strand the object holds
"""
self.exons.sort(cmp=self.start)
return self.exons
def addFeat(self, feat):
"""
Function: adds SeqFeature to feats keys
Returns : None
Args : feat - a single SeqFeature object
"""
if type(feat) == DNAFeature:
self.exons.append(feat)
else:
raise TypeError("Cannot add feature as it is not a type of DNAFeature")
def setTranslStart(self, transl_start):
"""
Function : accepts an non-negative int, sets the start position of the initiating ATG
Returns :
Args : transl_start
"""
if transl_start == None:
self.transl_start = None
return
elif type(transl_start) !=int:
raise TypeError("TranslStart cannot be set since it is not a type of int")
elif transl_start < 0:
raise ValueError("TranslStart cannot be set to a negative int")
else:
self.translStart = transl_start
def getTranslStart(self):
"""
Function: the start position of initiating ATG codon
Return : an int.
Args :
"""
return self.transl_start
def setTranslStop(self, transl_stop):
"""
Function: set the end position of initiating ATG codon
Return : None
Args : a positive int
"""
if transl_stop == None:
self.transl_stop = None
return
elif type(transl_stop) !=int:
raise TypeError("TranslStop cannot be set since it is not a type of int")
elif transl_stop < 0:
raise ValueError("TranslStop cannot be set to a negative int")
else:
self.translStop = transl_stop
def getTranslStop(self):
"""
Function: the end position of initiating ATG codon
Return : an int.
Args :
"""
return self.transl_stop
def setDisplayId(self, display_id):
"""
Function: set the display id
Returns : None
Args : display_id - a string, a preferred name for this
"""
if type(display_id) !=str:
raise TypeError("Cannot set displayId as it is not a type string")
else:
self.display_id = display_id
def getDisplayId(self):
"""
Function: get the display id
Returns : display_id - a string, a preferred name for this, e.g AT1G10555.1
Args :
"""
return self.display_id
Then, I got some code from my professor to test my file:
class TestGeneModelConstructor(unittest.TestCase):
def testGeneModelConstructor(self):
"""GeneModel constructor supports named arguments display_id,transl_start,transl_stop"""
p1.GeneModel(start=0,end=10,seq_name='something',strand=1,display_id='foobar',
transl_start=0,transl_stop=10)
def testGeneModelConstructorDefaults(self):
"""Default values for display_id, transl_start, transl_stop should be None"""
r = p1.GeneModel()
self.assertEquals(r.getDisplayId(),None)
self.assertEquals(r.getTranslStart(),None)
self.assertEquals(r.getTranslStop(),None)
def testGeneModelConstructorWrongTypeDisplayId(self):
"""Raise a TypeError if display_id is not a string."""
self.assertRaises(TypeError,p1.GeneModel,display_id=0)
def testGeneModelConstructorWrongTypeTranslStart(self):
"""Raise a TypeError if transl_start is not an int."""
self.assertRaises(TypeError,p1.GeneModel,transl_start='0')
def testGeneModelConstructorWrongTypeTranslStop(self):
"""Raise a TypeError if transl_stop is not an int."""
self.assertRaises(TypeError,p1.GeneModel,transl_stop='0')
def testGeneModelConstructorWrongValueTranslStart(self):
"""Raise a ValueError if transl_start is int < 0."""
self.assertRaises(ValueError,p1.GeneModel,transl_start=-1)
def testGeneModelConstructorWrongValueTranslStop(self):
"""Raise a ValueError if transl_stop is int < 0."""
self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1)
I have run it and got these errors:
ERROR: Default values for display_id, transl_start, transl_stop should be None
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 117, in testGeneModelConstructorDefaults
r = p1.GeneModel()
TypeError: __init__() takes at least 3 arguments (1 given)
======================================================================
ERROR: Raise a ValueError if transl_start is int < 0.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 136, in testGeneModelConstructorWrongValueTranslStart
self.assertRaises(ValueError,p1.GeneModel,transl_start=-1)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises
TypeError: __init__() takes at least 3 non-keyword arguments (2 given)
======================================================================
ERROR: Raise a ValueError if transl_stop is int < 0.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 140, in testGeneModelConstructorWrongValueTranslStop
self.assertRaises(ValueError,p1.GeneModel,transl_stop=-1)
File "/System/Library/Frameworks/Python.framework/Versions/2.6/lib/python2.6/unittest.py", line 336, in failUnlessRaises
TypeError: __init__() takes at least 3 non-keyword arguments (1 given)
I'm not sure what is wrong, I have tried to fixed it couple times, but haven't figure out what is wrong in my codes.
Alright, I have change my code in DNAFeature like this:
class DNAFeature(Range):
"""Represents a feature on a DNA sequence """
def __init__(self, seq_name = None, strand = 0, **kwargs):
"""
Function : represents a rane
Returns :
Args : strand, seqname, **kwargs
"""
Range.__init__(self, 0,10000, **kwargs)
self.setStrand(strand)
self.setSeqName(seq_name)
And then, get 3 more errors and 1 failure like this:
ERROR: DNAFeature on different sequence don't overlap
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 164, in testDiffSequenceOverlaps
r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo")
File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__
Range.__init__(self, 0, 10000, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'start'
======================================================================
ERROR: DNAFeatures on the same strand can overlap if ignore_strand is True.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 185, in testDiffStrandsDontOverlap
r1 = p1.DNAFeature(start=0,end=10,strand=1,seq_name="foo")
File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__
Range.__init__(self, 0, 10000, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'start'
======================================================================
ERROR: GeneModel constructor supports named arguments display_id,transl_start,transl_stop
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 113, in testGeneModelConstructor
transl_start=0,transl_stop=10)
File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 151, in __init__
DNAFeature.__init__(self, **kwargs)
File "/Users/trungpham/binf_prog/tpham22/project1/p1.py", line 95, in __init__
Range.__init__(self, 0, 10000, **kwargs)
TypeError: __init__() got multiple values for keyword argument 'start'
FAIL: Raise a TypeError if seq_name is not a string.
----------------------------------------------------------------------
Traceback (most recent call last):
File "/Users/trungpham/binf_prog/class/test/testProject1.py", line 98, in testDNAFeatureSeqNameConstructorWrongType
self.assertRaises(TypeError,p1.DNAFeature,seq_name=0)
AssertionError: TypeError not raised
There are several things wrong:
Firstly:
In your test function, testGeneModelConstructorDefaults, you have the comment: "Default values for display_id, transl_start, transl_stop should be None".
The problem you are seeing is that you have only set up the defaults on 1 of the 3 arguments; whereas this test function assumes you have set up defaults on all three. To fix this, you need to define the constructor like this:
def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs)
By having the keyword arguments, it will use the default of None. If you don't specify those keyword arguments explicitly, Python will complain (as it is currently doing).
Secondly:
You have to consider your superclass constructors. The Range superclass asks for two parameters: start and end.
def __init__(self, start, end):
However, when the DNAFeature constructor calls the Range superclass, it doesn't pass in begin or end:
Range.__init__(self, **kwargs)
This is where I think the error is now (I think before it was at the p1.GeneModel() call - there are probably different error lines in your two error messages).
To fix this, make the values for start and end into keyword parameters also. So instead of:
def __init__(self, start, end):
make it:
def __init__(self, start=0, end=10000):
You can then delete the following lines of code in your range constructor:
self.start = 0
self.end = 10000
That should at least get you past this error - you may find more errors that you have.
It appears that the tests are assuming that all parameters are passed by value. You need to give the positional arguments defaults.
Smashery is right. Try running this simplified code:
class GeneModel(object):
def __init__(self, transl_start=None, transl_stop=None, display_id = None, **kwargs):
pass
def testGeneModelConstructor():
g = GeneModel(start=0,end=10,seq_name='something',strand=1,display_id='foobar', transl_start=0,transl_stop=10)
def testGeneModelConstructorDefaults():
r = GeneModel()
testGeneModelConstructor()
testGeneModelConstructorDefaults()