Python:从字符串访问类属性

标签 python syntax

我有一个类似如下的类(class):

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 只适用于函数(据我所知)以及让 User 扩展 dict 并使用 self.__getitem__,但这也不起作用。最好的方法是什么?

最佳答案

x = getattr(self, source) 如果 source 命名 self 的任何属性,包括示例中的 other_data ,则将完美地工作.

关于Python:从字符串访问类属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1167398/

相关文章:

r - 使用df [col]访问列给出:错误 'x'对于 'sort.list'必须是原子的

c# - 在 C# MySqlCommand.CommandText 中使用 SQL 关键字

python - Python代码中的 "In [X]:"和 "Out[Y]:"是什么意思?

JavaScript 零位左移和右移在 Python 中等效吗?

python - Tkinter,我无法让 slider 显示所有按钮

php - 明显的语法错误

ruby - 如何重用 Vagrantfile 中引用行中的变量?

Python日志记录模块AttributeError : 'str' object has no attribute 'write'

python - 将数据框列名称从字符串格式更改为日期时间

ruby - Ruby中 `rescue`语句可以嵌套在什么结构中