如何在Python 2中从字符串引用变量

时间:2019-04-21 12:38:01

标签: python

我正在尝试从类中的字符串获取变量。我的意思是,当您输入作为类属性名称的输入时,它会找到该变量。例如

class Place:
    def __init__(self, north):

Place2 = ""
Place1 = Place(Place2)
Place2 = Place(Place1)

ask = raw_input("direction")
currentPlace = Place1
if (ask=="north"):
    currentPlace=currentPlace.north

3 个答案:

答案 0 :(得分:3)

使用getattr(currentPlace, 'north' )

此外,setattr()的工作方式与更新属性相同。以及用于检查属性是否存在的hasattr()

答案 1 :(得分:3)

使用Python 3提出一个示例(因为不推荐使用Python 2),并按照以下示例进行操作:

class A:

    def __init__(self):
        self.x = 10
        self.y = 22


a1 = A()

attribute_name = input("what attribute?: ")

result = getattr(a1, attribute_name, None)
print("Your attribute {} is: {}".format(attribute_name, result))

特定运行将产生:

what attribute?: x
Your attribute x is: 10

答案 2 :(得分:0)

您正在寻找getattr

示例:

class Place(object):

    def __init__(self, north):
        self.north = north

    def get(self, attr):
        return getattr(self, attr)

place = Place('here')
print(place.get('north'))

输出:

here