Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free.

in python I'm trying to access a instance variable where I need to use the value of another variable to determine the name: Example Instance Variable: user.remote.directory where it point to the value of 'servername:/mnt/.....' and user portion contains the userid of the user, such as joe.remote.directory

from another class I need to be able to access the joe.remote.directory using a variable that contains the user id of joe. I tried variable.remote.directory but it doesn't work, any suggestions?

share|improve this question
3  
There's almost always a better way to do this. While Python does allow you to access variables using string names, it's really kludgy and can actually slow down your whole program (when Python detects that you're doing this, it has to turn off a whole bunch of optimisations that it could otherwise do). –  Greg Hewgill Dec 22 '11 at 0:34

3 Answers 3

Unsure quite what you want, but I think getattr(obj, 'name') might help. See http://docs.python.org/library/functions.html#getattr

share|improve this answer

You can refer to instance variable called name of object obj this way:

obj.__dict__['name']

Therefore, if you have another variable prop which holds the name of the instance variable you'd like to refer to, you can do it this way:

obj.__dict__[prop]

If you find yourself needing this functionality, you should ask yourself whether it isn't in fact a good circumstance to use an instance of dict instead.

share|improve this answer

I would suggest you create an extra User-Object, which you pass to the appropriate Objects or functions as needed. You are being extremly vague, so it's hard to give you a more practical advice.

Example:

class User:
   def __init__(self, name, uid=None, remote=None, dir=None):
       self.name = name
       self.uid = uid
       self.remote = remote
       self.directory = dir

   def get_X(self)
       ...

   def create_some_curios_String(self):
       """ for uid = 'joe', remote='localhost' and directory = '/mnt/srv'
           this method would return the string:
           'joe@localhost://mnt/srv'
       """
       return '%s@%s:/%s' % (self.uid, self.remote, self.directory)


class AnotherClass:
    def __init__(self, user_obj):
        self.user = user_obj

class YetAnotherClass:
    def getServiceOrFunctionalityForUser(self, user):
        doWhatEverNeedsToBeDoneWithUser(user)
        doWhatEverNeedsToBeDoneWithUserUIDandRemote(user.uid, user.remote)

joe = User('Joe Smith', 'joe', 'localhost', '/mnt/srv')
srv_service = ServerService(joe.create_some_curios_String())
srv_service.do_something_super_important()
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.