pythonclassnameerrorbioservices

How to avoid a NameError when defining a class?


I am writing a class:

from bioservices import KEGGParser
class Retrieve_Data():
    def __init__(self):

        def hugo2kegg(self,gene_name,organism):
            s=KEGGParser()
            kegg_gene_entry = s.get(organism+':'+gene_name)
        return kegg_gene_entry


a = Retrieve_Data()

But when I run this I get a NameError:

NameError: global name 'kegg_gene_entry' is not defined

Could somebody tell me where i'm going wrong?


Solution

  • Your init can't return anything, and there's probably no sense in defining anything in it, if you're not going to use your definition. You probably want to get rid of your __init__ and do something like this:

    from bioservices import KEGGParser
    class Retrieve_Data():
        def hugo2kegg(self,gene_name,organism):
            s=KEGGParser()
            kegg_gene_entry = s.get(organism+':'+gene_name)
            return kegg_gene_entry
    
    
    a = Retrieve_Data()
    

    You don't need an __init__, unless you want things to happen immediately after the object is instantiated.

    If you wanted an init that didn't do anything, you would need to have something under it:

    class Retrieve_Data():
        def __init__(self):
            pass # we'll add more later?
    

    or

    class Retrieve_Data():
        def __init__(self):
            '''not doing anything now, maybe we'll write an init later?'''
    

    and then you could go on to define another function/method for this object.