2

I have a class which defines data attributes.

class channel:
    def __init(self,var1, var2):
        self.var1 = var1
        self.var2 = var1
        #etc

So far so simple. But what I'd like to do is to have a method that specifies which data attribute to use so that I can generically use it to do the same thing with different data attriutes depending on the arguments, something like (obviously this is not right)

def fun(list_of_channels, var1):
    for chan in list_of_channels:
        #use chan.var1

but be able to use var2 as an argument to access chan.var2 if I called

fun(list_of_channels,var2)

Is there an obvious way to do this that I've missed?

2 Answers 2

9

You can use getattr like this:

def fun(list_of_channels, attr_name):
    for chan in list_of_channels:
        attr = getattr(chan, attr_name)
        ...
Sign up to request clarification or add additional context in comments.

Comments

3

Is the getattr function what you need?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.