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,v开发者_运维技巧ar2)
Is there an obvious way to do this that I've missed?
You can use getattr like this:
def fun(list_of_channels, attr_name):
for chan in list_of_channels:
attr = getattr(chan, attr_name)
...
Is the getattr
function what you need?
精彩评论