tags:

views:

573

answers:

4

I have a class like the following:

class User:
    def __init__(self):
        self.data = []
        self.other_data = []

    def doSomething(self, source):
        // if source = 'other_data' how to access self.other_data

I want to pass a string for the source variable in doSomething and access the class member of the same name.

I have tried getattr which only works on functions (from what I can tell) as well as having User extend dict and using self.__getitem__, but that doesn't work either. What is the best way to do this?

+6  A: 

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, include the other_data in your example. What code exactly have you tried, that appears to be failing?!

Alex Martelli
+1  A: 

Extending Alex's answer slightly:

class User:
    def __init__(self):
        self.data = [1,2,3]
        self.other_data = [4,5,6]
    def doSomething(self, source):
        dataSource = getattr(self,source)
        return dataSource

A = User()
print A.doSomething("data")
print A.doSomething("other_data")
will yield:
[1, 2, 3]
[4, 5, 6]

However, personally I don't think that's great style - getattr will let you access any attribute of the instance, including things like the doSomething method itself, or even the __dict__ of the instance. I would suggest that instead you implement a dictionary of data sources, like so:

class User:
    def __init__(self):

        self.data_sources = {
            "data": [1,2,3],
            "other_data":[4,5,6],
        }

    def doSomething(self, source):
        dataSource = self.data_sources[source]
        return dataSource

A = User()

print A.doSomething("data")
print A.doSomething("other_data")
again yielding:
[1, 2, 3]
[4, 5, 6]
Markus
I didn't explain properly... my apologies. I am able to get the data via the string. However, I am having problems setting the data using the above methods. Specifically I have tried getattr(self, "other_data") = [1, 2, 3]as well as self.__setitem__("other_data", [1, 2, 3])
sberry2A
+1  A: 

While typing my last comment I realized there was probably a counterpart to getattr, setattr. That is what I was looking for.

Thanks to everyone. I see that implementing a data_sources dict might be the better way to go anyway.

Thanks again.

sberry2A
+1  A: 

A picture's worth a thousand words:

>>> class c:
        pass
o = c()
>>> setattr(o, "foo", "bar")
>>> o.foo
'bar'
>>> getattr(o, "foo")
'bar'
Robert Rossney