+-
Python:从字符串访问类属性
参见英文答案 > How to access object attribute given string corresponding to name of that attribute                                    2个
我有一个类如下:

class User:
    def __init__(self):
        self.data = []
        self.other_data = []

    def doSomething(self, source):
        // if source = 'other_data' how to access self.other_data

我想在doSomething中为源变量传递一个字符串,并访问同名的类成员.

我试过getattr只能用于函数(从我能说的)以及用户扩展dict并使用self .__ getitem__,但这也不起作用.做这个的最好方式是什么?

最佳答案
x = getattr(self,source)将完美地工作,如果源名称为self的任何属性,包括示例中的other_data.
点击查看更多相关文章

转载注明原文:Python:从字符串访问类属性 - 乐贴网