相关疑难解决方法(0)

Python:从string访问类属性

我有一个类如下:

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

    def doSomething(self, source):
        // if source = 'other_data' how to access self.other_data
Run Code Online (Sandbox Code Playgroud)

我想传入源变量的字符串doSomething并访问同名的类成员.

我已经尝试过getattr只能在函数上工作(从我能说的)以及User扩展dict和使用self.__getitem__,但这也不起作用.做这个的最好方式是什么?

python syntax

152
推荐指数
4
解决办法
9万
查看次数

如何访问对应于该属性名称的给定字符串的对象属性

如何设置/获取t给定的属性值x.

class Test:
   def __init__(self):
       self.attr1 = 1
       self.attr2 = 2

t = Test()
x = "attr1"
Run Code Online (Sandbox Code Playgroud)

python attributes object

121
推荐指数
2
解决办法
7万
查看次数

标签 统计

python ×2

attributes ×1

object ×1

syntax ×1