Off topic:Requiring a "setter" method to modify instance variables of a python object
0
0
Entering edit mode
8.4 years ago
xgeneral57 ▴ 10

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 • 2.3k views
ADD COMMENT
This thread is not open. No new answers may be added
Traffic: 2000 users visited in the last hour
Help About
FAQ
Access RSS
API
Stats

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6