用户登录
用户注册

分享至

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

  • 作者: 道人山农场
  • 来源: 51数据库
  • 2023-01-05

问题描述

How do you set/get the values of attributes of t given by x?

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

t = Test()
x = "attr1"

解决方案

There are built-in functions called getattr and setattr

getattr(object, attrname)
setattr(object, attrname, value)

In this case

x = getattr(t, 'attr1')
setattr(t, 'attr1', 21)

软件
前端设计
程序设计
Java相关