7

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?

1
  • 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). Commented Dec 22, 2011 at 0:34

3 Answers 3

15

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

Sign up to request clarification or add additional context in comments.

Comments

9

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.

Comments

1

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()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.