Python: accessing an instance variable using the name containing the variable

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

from another class, I need to have access to joe.remote.directory using a variable containing the user id joe. I tried the variable.remote.directory file, but it does not work, any suggestions?

+5
source share
3 answers
+9

, name obj :

obj.__dict__['name']

, prop, , , :

obj.__dict__[prop]

, , dict.

+3

User-Object, . , .

:

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

All Articles