jon*_*onH 2 python class instance
***EDIT2:对于损坏的代码感到抱歉.这是工作代码,说明了同样的问题:
class bead():
def printmsg(a):
print('test message')
chain1=bead()
x='chain1'
eval(x + '.printmsg()')
Run Code Online (Sandbox Code Playgroud)
***编辑:谢谢gnibbler回答原始问题.这是我的问题更好的措辞版本:
class bead():
def msg():
print('test message')
x='chain1'
y='bead1'
eval(x + '.' + y + '=bead()')
chain1.bead1.msg()
Run Code Online (Sandbox Code Playgroud)
输出:'测试消息'
有什么更好的方法呢?
原始问题:
脚本:
class testClass():
test1='test1 text'
x='testClass'
y='test1'
eval(x + '.' + y)
Run Code Online (Sandbox Code Playgroud)
输出:'test1 text'
有没有更好的方法呢?
***编辑:getattr()用于从类中提取信息.谢谢gnibbler.让我稍微改变一下这个问题:
我可以用什么而不是:
x ='chain1'y ='mol1'
Joh*_*ooy 12
eval()你可以说,而不是
getattr(locals()[x], y)
Run Code Online (Sandbox Code Playgroud)
要么
getattr(locals().get(x), y)
Run Code Online (Sandbox Code Playgroud)
你是这个意思吗?