【问题标题】:Python: access class property from string [duplicate]Python:从字符串访问类属性[重复]
【发布时间】:2021-11-03 07:47:41
【问题描述】:

我有一个类似如下的课程:

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__,但这也不起作用。最好的方法是什么?

【问题讨论】:

    标签: python syntax


    【解决方案1】:

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

    【讨论】:

    • (意识到这是一个旧线程)。由于听写,我很困惑/总是忘记这一点。如果我想从字典中获取值,我可以说:myDict.get('keyy'),所以我希望属性以相同的方式工作:myObject.getattr('attr_name')。但相反,他们将对象作为第一个参数......可以这样做,但明显的不一致是我遇到麻烦的原因。
    【解决方案2】:

    稍微扩展亚历克斯的回答:

    class User:
        def __init__(self):
            self.data = [1,2,3]
            self.other_data = [4,5,6]
        def doSomething(self, source):
            dataSource = getattr(self,source)
            return dataSource
    
    A = User()
    print A.doSomething("data")
    print A.doSomething("other_data")
    

    将产生:

    [1、2、3] [4、5、6]

    但是,我个人认为这不是很好的风格 - getattr 将允许您访问实例的任何属性,包括 doSomething 方法本身,甚至是实例的 __dict__。我建议您改为实现一个数据源字典,如下所示:

    class User:
        def __init__(self):
    
            self.data_sources = {
                "data": [1,2,3],
                "other_data":[4,5,6],
            }
    
        def doSomething(self, source):
            dataSource = self.data_sources[source]
            return dataSource
    
    A = User()
    
    print A.doSomething("data")
    print A.doSomething("other_data")
    

    再次屈服:

    [1、2、3] [4、5、6]

    【讨论】:

    • 我没有正确解释......我很抱歉。我能够通过字符串获取数据。但是,我在使用上述方法设置数据时遇到问题。具体来说,我尝试过 getattr(self, "other_data") = [1, 2, 3] 以及 self.__setitem__("other_data", [1, 2, 3])
    • @sberry2A, getattr() 仅用于获取,setattr() 用于设置。您不能分配给来自getattr() 的返回值。
    【解决方案3】:

    一张图胜过千言万语:

    >>> class c:
            pass
    o = c()
    >>> setattr(o, "foo", "bar")
    >>> o.foo
    'bar'
    >>> getattr(o, "foo")
    'bar'
    

    【讨论】:

    • 我特别喜欢这个答案,因为它简单地说明了 getattr() 函数也可以在类方法之外工作。
    【解决方案4】:
    • getattr(x, 'y') 等价于 x.y
    • setattr(x, 'y', v) 等价于 x.y = v
    • delattr(x, 'y') 等价于 del x.y

    【讨论】:

    • 如何根据v的值串访问x.y
    • @user2284570:如果v 包含字符串'y',则getattr(x, v) 给出x.y 的值。
    • @md2perpe 但事实并非如此。
    • @user2284570:那你的情况如何?
    猜你喜欢
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多