python:使用包含变量的名称访问实例变量

python:使用包含变量的名称访问实例变量,python,variables,instance,Python,Variables,Instance,在python中,我试图访问一个实例变量,其中我需要使用另一个变量的值来确定名称:示例实例变量:user.remote.directory,其中它指向“servername:/mnt/…”的值,并且用户部分包含用户的用户ID,例如joe.remote.directory 从另一个类中,我需要能够使用包含joe用户id的变量访问joe.remote.directory。我尝试了variable.remote.directory,但它不起作用,有什么建议吗?您可以通过以下方式引用对象obj的名为na

在python中,我试图访问一个实例变量,其中我需要使用另一个变量的值来确定名称:示例实例变量:user.remote.directory,其中它指向“servername:/mnt/…”的值,并且用户部分包含用户的用户ID,例如joe.remote.directory


从另一个类中,我需要能够使用包含joe用户id的变量访问joe.remote.directory。我尝试了variable.remote.directory,但它不起作用,有什么建议吗?

您可以通过以下方式引用对象
obj的名为
name
的实例变量:

obj.__dict__['name']
obj.__dict__[prop]
因此,如果您有另一个变量
prop
,其中包含您要引用的实例变量的名称,您可以这样做:

obj.__dict__['name']
obj.__dict__[prop]

如果您发现自己需要此功能,您应该问问自己,实际上使用
dict
的实例是否不是一个好环境。

不确定您想要什么,但我认为
getattr(obj,'name')
可能会有所帮助。请参见

我建议您创建一个额外的用户对象,并根据需要将其传递给相应的对象或函数。你非常含糊,所以很难给你一个更实际的建议

例如:

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

几乎总是有更好的方法来做到这一点。虽然Python确实允许您使用字符串名称访问变量,但它确实很麻烦,而且实际上会减慢整个程序的速度(当Python检测到您正在这样做时,它必须关闭一系列本来可以进行的优化)。