Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple python question: accessing class data member

Tags:

python

class

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?

like image 308
Chris Avatar asked Nov 18 '25 14:11

Chris


2 Answers

You can use getattr like this:

def fun(list_of_channels, attr_name):
    for chan in list_of_channels:
        attr = getattr(chan, attr_name)
        ...
like image 54
mouad Avatar answered Nov 20 '25 05:11

mouad


Is the getattr function what you need?

like image 38
ulidtko Avatar answered Nov 20 '25 04:11

ulidtko



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!