如何设置/获取 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.