小编jon*_*onH的帖子

python:从变量名创建实例

***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'

python class instance

2
推荐指数
1
解决办法
1028
查看次数

标签 统计

class ×1

instance ×1

python ×1