8wDlpd.png
8wDFp9.png
8wDEOx.png
8wDMfH.png
8wDKte.png

如何访问(获取或设置)对象属性给定与该属性名称对应的字符串

Aliaz 1月前

20 0

如何设置/获取 x 给出的 t 的属性值?class Test:def __init__(self): self.attr1 = 1 self.attr2 = 2t = Test()x = \'attr1\' 请注意,相同的技术......

给出 t 的属性值 x

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

t = Test()
x = "attr1"

Note that the same technique also covers the issue of 从字符串调用方法 . Fundamentally, that is two problems: accessing the method (which is just an instance of the same problem here), and calling what was accessed (which is trivial, and works the same way as if it had been accessed normally).

In fact, 使用模块名称(字符串)调用模块的函数 is really the same problem as well - but it may not be obvious that a module is an "object" with "attributes" that work the same way.

帖子版权声明 1、本帖标题:如何访问(获取或设置)对象属性给定与该属性名称对应的字符串
    本站网址:http://xjnalaquan.com/
2、本网站的资源部分来源于网络,如有侵权,请联系站长进行删除处理。
3、会员发帖仅代表会员个人观点,并不代表本站赞同其观点和对其真实性负责。
4、本站一律禁止以任何方式发布或转载任何违法的相关信息,访客发现请向站长举报
5、站长邮箱:yeweds@126.com 除非注明,本帖由Aliaz在本站《class》版块原创发布, 转载请注明出处!
最新回复 (0)
  • @ihightower 请参阅如何根据字符串中的名称获取变量的值?简而言之,如果范围未知,就没有通用的方法可以做到这一点。afult 的解决方案假设它是一个全局变量,尽管它可能是全局变量。

返回
作者最近主题: