0

I am getting used to classes in python and I was trying to use them to make a project smarter. It concerns rivers morphodynamics.

I have 3 main inputs:

  • geometry
  • hydrograph
  • grain size distribution

Here is how I organized my project:

  1. config.ini file where I define the 3 main inputs
  2. reader.py where I read the config.ini (with the configparser library)
  3. hydraulics.py file where I perform hydraulics calculations
  4. bedload.py file where I compute the bedload
  5. main.py file where the other files are called

Inside the bedload.py file I have a single class called "formula" which contains several methods, i.e. several bedload formulas.

class formula:
    def __init__(...):
        ....

    def formula1(...):
        ....

    def formula2(...):
        ....
    ....

    def formulan(...):
        ....

Each formula gives to arrays as output.

As an input I get the formula the user wants to use, and I choose it inside the main.py file as follows

import bedload
if formula == 'formula1':
    bl = bedload.formula(...)
    bl.formula1(...)

Is there a way to pass the input name to the class and choose the formula inside the class? Or maybe even a way to do what I am trying to do in a more pythonic way?

EDIT: to my understanding, the question suggested as similar to mine is indeed similar to mine, but the answers there are not exactly what I was looking for, which is what thebjorn suggested.

brodegon
  • 231
  • 2
  • 12
  • You can use [getattr()](https://docs.python.org/3/library/functions.html#getattr) to find attributes by string name. – quamrana Jul 06 '21 at 14:08
  • instance.getattr, check https://stackoverflow.com/questions/3521715/call-a-python-method-by-name – Yuri Jul 06 '21 at 14:09
  • Does this answer your question? [Call a Python method by name](https://stackoverflow.com/questions/3521715/call-a-python-method-by-name) – Pranav Hosangadi Jul 06 '21 at 14:22
  • Thanks everyone, all your comment have been helpful, they go towards the same direction as thebjorn answer, which I marked as correct. – brodegon Jul 06 '21 at 15:19

2 Answers2

1

You can override bracket lookup and getattr:

class formula:
   ...
   def __getitem__(self, name):
       return getattr(self, name)

bl = bedload.formula(...)
bl['fomula1'](...)
thebjorn
  • 26,297
  • 11
  • 96
  • 138
0

Use operator.methodcaller:

from operator import methodcaller


formula_name = "formula1"

bedload = formula()
methodcaller(formula_name, ...)(bedload)  # equiv. to bedload.formula1(...)
chepner
  • 497,756
  • 71
  • 530
  • 681