user2020312
user2020312

Reputation: 3

Using variables as an attribute for a module?

Let's say I've got two variables: "choice" = ii7 and "scale" = C.

This library has a function to figure out notes in any particular musical chord by running this:

chords.ii7(scale)

When scale = C, it'll list the notes of the ii7 chord in the scale of C.

If I had to use the variable "choice" in place of including ii7 in the code itself, how could I go about it? It would definitely be a lot easier to search if I knew what to search for, but I'm a total beginner. This is just to top off the rest of this particular program, and learn something new. Apologies if I worded the title wrong. Thanks in advance!

Upvotes: 0

Views: 85

Answers (1)

Volatility
Volatility

Reputation: 32300

Use getattr

getattr(chords, choice)(scale)

This is assuming choice = 'ii7'.

getattr basically takes two parameters - the first being an object, the second being a string. It searches for an attribute that has the same name as the string, and returns it. In this case getattr(chords, choice) returns chords.ii7, which you then have to call.

Upvotes: 1

Related Questions