Python:从字符串访问类属性 [英] Python: access class property from string

查看:64
本文介绍了Python:从字符串访问类属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个如下所示的类:

I have a class like the following:

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 中的源变量传递一个字符串并访问同名的类成员.

I want to pass a string for the source variable in doSomething and access the class member of the same name.

我尝试过 getattr 只适用于函数(据我所知)以及让 User 扩展 dict 并使用 self.__getitem__,但这也不起作用.这样做的最佳方法是什么?

I have tried getattr which only works on functions (from what I can tell) as well as having User extend dict and using self.__getitem__, but that doesn't work either. What is the best way to do this?

推荐答案

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

x = getattr(self, source) will work just perfectly if source names ANY attribute of self, including the other_data in your example.

这篇关于Python:从字符串访问类属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆