如何根据其值来检索变量名称

时间:2015-05-12 01:19:35

标签: python class

class type_name:
    def __init__(self, *field_names):
        self.x = field_names[0]
        self.y = field_names[1]
        self._fields = [x for x in field_names]
    def get_y(self):
        return self.y

    def __getitem__(self, ind):
        fstr = 'self.get_' + str(self._fields[ind]) #this would give me 5 i want self.y so I construct a string such as 'self.get_y()'
        #and then return eval on that string to return the value

使用上面的代码,

Point = pnamedtuple('Point', ['x','y'], mutable = False) 
origin = Point(0,5)
print(origin[1])

它也应该与origin ['y']

一起使用

0 个答案:

没有答案