How to call a method with a method name as a string

I am using the Biopython constraint class to perform in silicone constraints. It is my understanding that in order to digest a specific sequence with a specific enzyme, the .catalyze () method must be implemented.

digestTuple = Restriction.EcoRI.catalyse(this_seq)  # Or whichever enzyme is desired.

      

I am currently using a conditional expression to determine which enzyme is used as input. For example:

RS = restrictionSite         # From user
amb = IUPACAmbiguousDNA()
this_seq = Seq(sequence, amb) # sequence from user

if RS == 'EcoRI':
    digestTuple = Restriction.EcoRI.catalyse(this_seq)

      

I use conditional expression for any enzymes that I would foresee for myself. It takes a bunch of lines of code and is inefficient. I would like to be able to search for membership in the restriction set of all possible Restriction.AllEnzymes enzymes. Something like that:

if RS in Restriction.AllEnzymes:
    digestTuble = Restriction.RS.catalyze(this_seq)

else:
    print('Please type in enzyme name correctly')

      

This problem is because python doesn't equate:

RS = "EcoRI" 
digestTuple = Restriction.RS.catalyze(this_seq)

      

from

digestTuple = Restriction.EcoRI.catalyze(this_seq) 

      

Because it tries to use the string name associated with the enzyme and does not call the method itself.

Is there a way to call this method using a single condition that looks for all possible enzymes?

Maybe something like this Calling a method by its name , but in python?

The technical wording on this is a bit confusing for me, so I probably didn't explain the problem very accurately. I am happy to answer any clarifying questions.

thank

+3


source to share


2 answers


Use getattr()

for example:



RS = "EcoRI"
digestTuple = getattr(Restriction, RS).catalyze(this_seq)

      

+4


source


Easier than:

getattr(your_object,"methodname")()

      

Example:

class My_Class:
    def print_hi(self):
        print 'hi'

a = My_Class()

getattr(a,'print_hi')()

      



output:

hi

      

In your case:

RS = "EcoRI" 
digestTuple = getattr(Restriction, RS).catalyze(this_seq) 

      

+4


source







All Articles