使用eval来定义Python类数据属性

Waw*_*zek 0 python eval class

我想知道是否可以使用eval来创建类数据属性.像下面的代码:

class Test:
    def __init(self):
        matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']
        for matrix in matrix_names:
            print matrix
            operation = "self.%s = self.__matrix_read(%s)" %\
             (matrix, matrix)
            eval(operation)

    def __matrix_read(self, filename):
        return (read(".matrix/%s.csv"%filename))
Run Code Online (Sandbox Code Playgroud)

在iPython中我得到:

File "<string>", line 1
   self.F = self.__matrix_read(F)
       ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

Pas*_*eBT 7

您可以在函数中使用setattr build:

class Test:
    def __init(self):
        matrix_names = ['F', 'B', 'H', 'Q', 'R', 'x', 'P']
        for matrix in matrix_names:
            print matrix
            setattr(self, matrix, self.__matrix_read(matrix))
Run Code Online (Sandbox Code Playgroud)