Python AttributeError when running nosetest - python

I have a file called Model.py that contains the code
class ModelCalibrator():
def __init__(self):
self.file1 = 'Mortality_Population.txt'
self.file2 = 'Deaths_1x1_adj.txt'
self.MaxAge = 101
self.MinAge = 18
self.basisAges = np.array([18, 50, 100])[np.newaxis]
self.mortalityData = PopulationData()
self.deathRateData = DeathRateData()
(self.age, self.phis) = computeBasisFunctions(ModelCalibrator)
def computeBasisFunctions(mc):
MaxAge = mc.MaxAge
MinAge = mc.MinAge
age = np.arange(MinAge, MaxAge)[np.newaxis]
basisAges = mc.basisAges
#calculations
...
return (age, phis)
In a separate test.py file I am running nosetests using the code
def testMC():
data = ModelCalibrator()
Phi = data.phis()
assert_equal(Phi[0], 1)
This keeps telling me that I have an attributeerror: type object 'ModelCalibrator' has no attributes 'MaxAge'. Can anyone tell me where I am going wrong please?

On this line, you are passing in the class instead of the object. Try replacing ModelCalibrator with self. The class is only a template for the object. self represents the current object with all of the properties set.
(self.age, self.phis) = computeBasisFunctions(self)
Alternatively, if you want these to be accessible without an object, you could set MaxAge and MinAge as class variables by moving them outside of the __init__ function, but inside the class as shown here.

Related

How can I recreate a class object for testing, tried debugging and printing relevant items but can't get it?

I have the following class:
class MessageContext:
def __init__(self, raw_packet, packet_header, message_header, message_index):
self.raw_packet = raw_packet
self.pkthdr = packet_header
self.msghdr = message_header
self.msgidx = message_index
self.msg_seqno = packet_header.seqno + message_index
And a function that creates objects using the above class:
def parsers(data):
...
context = MessageContext(None, PacketAdapter(), msghdr, 0)
self.on_message(rawmsg, context)
I am trying to recreate context, and when i set a breakpoint just after it and print context, I get:
<exchanges.protocols.blahblah.MessageContext object at 0x7337211520>
I have left out quite a bit of code as it is very long, but if any more information is needed I am happy to provide of course.
Here is what I get when I print the arguments of MessageContext:
print(PacketAdapter()) -> <exchanges.blahblah.PacketAdapter object at 0x7f60929e1820>
Following the comments below, the PacketAdapter() class looks like this:
class PacketAdapter:
def __init__(self):
self.seqno = 0

My function works on its own but not callable from class

I've made a class as follow:
class Plugins:
def __init__(self):
pass
def voter_rep(self, loc, start_header, end_header):
self.loc = loc
ocr_xml = AbbyyXML(loc)
xml_doc = XMLDoc(ocr_xml, CONSTANTS)
xml_doc.split_words("", False)
self.start_header = start_header
self.end_header = end_header
header_pages = xml_doc.se_page(start_header, end_header)
## and stuff
voter_dict = {'Voter':[], 'Record_Key':[], 'Comments':[]}
## and stuff
return voter_dict, rep_dict
if I run the method function on its own and outside of the class it works totally fine, namely if I write the function as:
def voter_rep(loc, start_header, end_header):
ocr_xml = AbbyyXML(loc)
xml_doc = XMLDoc(ocr_xml, CONSTANTS)
xml_doc.split_words("", False)
header_pages = xml_doc.se_page(start_header, end_header)
## and stuff
voter_dict = {'Voter':[], 'Record_Key':[], 'Comments':[]}
## and stuff
return voter_dict, rep_dict
in the function alone I get rid of self and will just have voter_rep(loc, start_header, end_header) but when I want to call it from the class I do plugins.voter_rep(loc, start_header, end_header) which does not work, and it returns:
NameError: name 'plugins' is not defined
I wonder why is it that my function works on its own but not callable from the class?
You can do
plugins = Plugins()
loc = #some val
start_header = #some val
end_header = #some val
plugins.voter_rep(loc, start_header, end_header)
As the error message shows, you are using small 'p' instead of capital. Also since it is not a static function, so it is not good to call it via class name.
Plugins.voter_rep(loc, start_header, end_header)
Take note of the capital letter.

How do I pass in variables to a Class in python, and then have those variables be used in other called classes/objects?

I have a class called createEmbeds and I want to pass the variables pretrained_path, ffn_weight_file, bert_ffn_weight_file, and embedding_file to it.
I then want those variables to be passed when creating new objects within this class. I have imported other classes, and now I want to make instances of them by passing in variables.
I then want to pass those objects to another object.
Here is my attempt
from Scripts.predictor_functions import QAEmbed, FaissTopK, RetreiveQADoc
class createEmbeds:
def __init__(self, pretrained_path = None, ffn_weight_file = None, \
bert_ffn_weight_file = 'models/bertffn_crossentropy/bertffn', embedding_file = 'qa_embeddings/bertffn_crossentropy.csv'):
self.pretrained_path = pretrained_path
self.ffn_weight_file = ffn_weight_file
self.bert_ffn_weight_file = bert_ffn_weight_file
self.embedding_file = embedding_file
def get_qa_embed(self):
qa_embed = QAEmbed(
pretrained_path=self.pretrained_path,
ffn_weight_file=self.ffn_weight_file,
bert_ffn_weight_file=self.bert_ffn_weight_file
)
return qa_embed
def get_faiss_topk(self):
faiss_topk = FaissTopK(self.embedding_file)
return faiss_topk
doc = RetreiveQADoc(get_qa_embed(self), get_faiss_topk(self))
I am getting a
NameError: name 'self' is not defined
Error
Full error
1 frames
/usr/local/lib/python3.6/dist-packages/Scripts/inference_question_to_topk_functions2.py in createEmbeds()
26 return faiss_topk
27
---> 28 doc = RetreiveQADoc(get_qa_embed(self), get_faiss_topk(self))
29
30 # print(doc.predict('i have a headache.',
NameError: name 'self' is not defined

Adding a new object to a class with user-input(input) in python

I am trying to add new objects to a class(emne) but the new instances of the class needs to be created using user input. So i need a way to be able to chose the name for the object and set some of the values of the objects with user input.
I have already tried to create a function that passes the value of the user input into a x = emner(x) to create it but it only returns:
AttributeError: 'str' object has no attribute 'fagKode'
so i think my issue is that the value of the input is created as a string so that it is not understood as a way to create the function
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne():
nyttEmne = input("test:")
nyttEmne=Emne(nyttEmne)
expected result is that the code creates a new instance of the class.
If by choosing a name you mean your fagKode attribute, what you need is:
fagKode = input('Enter code: ')
Emne(fagKode)
You're adding the instances of Enme to the list in the constructor, so you don't need to save them to a variable.
Alternatively, you can handle that in the function:
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
def leggTilEmne():
nyttEmne = input("test:")
enme.append(Emne(nyttEmne))
I'm not sure what exactly you are asking, since you haven't responded to the comments. So,
emne=[]
class Emne:
def __init__(self,fagKode):
self.fagKode = fagKode
self.karakter = ""
emne.append(self)
def leggTilEmne(self, value): # <--- is this what you want
self.nyttEmne= Emne(value)
This is an example of when to use a class method. __init__ should not be appending to a global variable, though. Either 1) have the class method append to a class attribute, or 2) have it return the object and let the caller maintain a global list.
emne = []
class Emne:
emne = []
def __init__(self, fag_kode):
self.fag_kode = fag_kode
self.karakter = ""
#classmethod
def legg_til_emne_1(cls):
nytt_emne = input("test:")
cls.emne.append(cls(nytt_emne))
#classmethod
def legg_til_emne_2(cls):
nyttEmne = input("test:")
return cls(nyttEmne)
Emne.legg_til_emne_1() # Add to Emne.emne
e = Emne.legg_til_emne_2()
emne.append(e)

Why does this print the memory location of an object rather than what I want?

I'm not sure what's happening when I print my dictionary.
In Python 3, I have a dictionary of parse_blast objects called transSwiss. Each object's proteinID is the key with the entire object as the value.
I can print transSwiss in it's entirety and I can also print blasto.protein, but not when I combine them to get a dictionary value. I'm not sure what is happening when I use:
print(transSwiss[blasto.protein])
<__main__.parse_blast object at 0x000000373C5666A0>
Here is the code
class parse_blast(object):
def __init__(self, line):
#Strip end-of-line and split on tabs
self.fields = line.strip("\n").split("\t")
self.transcriptId, self.isoform = self.fields[0].split("|")
self.swissStuff = self.fields[1].split("|")
self.swissProtId = self.swissStuff[3]
self.percentId = self.fields[2]
def filterblast(self):
return float(self.percentId) > 95
class parse_matrix(object):
#Consider __init__ as a Constructor
def __init__(self, matrix_lines):
(self.protein,
self.Sp_ds,
self.Sp_hs,
self.Sp_log,
self.Sp_plat) = matrix_lines.strip("\n").split("\t")
def separate_tuples(one_tuple):
return "\t".join(one_tuple)
blastmap = map(parse_blast, blast_output.readlines())
filtered = filter(parse_blast.filterblast, blastmap)
matrixmap = map(parse_matrix, matrix_output.readlines()[1:])
transSwiss = {blasto.transcriptId:blasto for blasto in filtered}
for matrixo in matrixmap:
print(transSwiss[matrixo.protein])
Because your object is defined by you, you also need to tell python how you want it to print. You can do this by defining a function called "__str__" that returns how you want to print your object.
https://en.wikibooks.org/wiki/Python_Programming/Classes#str

Categories

Resources