This is a test version of Biostars. For the public version, visit https://www.biostars.org.
Requiring a "setter" method to modify instance variables of a python object

I was wondering if there is any way to prevent the external modification of instance variables in a python object by requiring the use of a "setter" method. For example, if g = gene(gene_info = {'id':'gene1', 'start':1200, end':2520}), I'd like g.gene_info = {'id':'gene1', 'start':1556, 'end':2520}) as well as g['start'] = 1556 to throw an error asking to use set_geneInfo method instead. This will be particularly useful when one needs to modify a number of other attributes related to gene_info after modifying gene_info. Here's an sample code, where variable gene_loc needs to be updated each time one modifies gene_info:

class gene(object):
    def __init__(self,gene_info):
        self.set_geneInfo(gene_info)

    def set_geneInfo(self,gene_info):
        """
        gene_info has to be a dictionary
        """
        if not isinstance(gene_info,dict):
            raise TypeError('gene_info must be a dictionary')

        self.gene_info = gene_info
        self.get_gene_loc()  # Gene gene location in the genome

    def get_gene_loc(self):
        """
        NOTE: self.gene_loc (gene location) needs to get updated each time one modifies gene_info
        """
        self.gene_loc = (self.gene_info['start' , self.gene_info['end'])

if __name__ == '__main__':
        g = gene(gene_info = {'id':'gene1', 'start':1200, 'end':2520}))
    print g.gene_loc  # Show gene location
    g.gene_info = {'id':'gene1', 'start':1556, 'end':2520}) # I'd like this to throw an error asking to use set_geneInfo so that gene_loc gets updated too
    print g.gene_loc  # checks if gene_loc was updated
    g.gene_info['start'] = 1800 # I'd like this to throw an error asking to use set_geneInfo so that gene_loc gets updated too
    print g.gene_loc  # checks if gene_loc was updated.
python object

Hi xgeneral57, this is not a bioinformatics question. You will find better answers in sites like stackoverflow.

For this reason we have closed your question. This allows us to keep the site focused on the topics that the community can help with.

If you disagree please tell us why in a reply below, we'll be happy to talk about it.

Cheers!

PS.

I think what you need are python property decorators

0 answers

No answers yet.

Log in to answer this question.