Chris
Chris

Reputation: 43

Simple python question: accessing class data member

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?

Upvotes: 2

Views: 646

Answers (2)

ulidtko
ulidtko

Reputation: 15560

Is the getattr function what you need?

Upvotes: 3

mouad
mouad

Reputation: 70021

You can use getattr like this:

def fun(list_of_channels, attr_name):
    for chan in list_of_channels:
        attr = getattr(chan, attr_name)
        ...

Upvotes: 9

Related Questions