James Draper - 9 months ago 65

Python Question

In Python 3.x is it possible to dynamically choose a function inside of a function or class?

For example in the function below, instead of relying on conditional statements could just enter the method that I would like to use?

`def npMethodChooser(n,m,method):`

if method == "mean":

return np.random.rand(n,m).mean(axis=1)

if method == "std":

return np.random.rand(n,m).std(axis=1)

Answer Source

Dynamic attribute lookup may be done by using `getattr`

function.

```
def npMethodChooser(n, m, method):
return getattr(np.random.rand(n,m), method)(axis=1)
```