【发布时间】:2014-03-22 10:08:17
【问题描述】:
我正在使用 Python 2.5 在 Maya 中工作,编写一个动态热键管理器类,但在尝试分配特定于实例的命令时遇到了麻烦,因为 nameCommands 在 mel 中表示为字符串。我最终得到的命令看起来像:
<bla.Bla instance at 0x0000000028F04388>.thing = 'Dude'
我已经看过很多关于 repr 和 eval 的话题,但我下面的测试示例失败了。
class Foo:
pass
f = Foo()
f.thing = 'Jeff'
rep = repr(f)
y = eval(rep) # errors here
name = y.thing
# Error: invalid syntax
# Traceback (most recent call last):
# File "<maya console>", line 7, in <module>
# File "<string>", line 1
# <__main__.Foo instance at 0x00000000294D8188>
# ^
# SyntaxError: invalid syntax #
我假设我想要的是某种从字符串中获取该实例的正确对象的方法。 如果我知道它的样子,我可以将字符串格式化为可评估的命令。 see my cgtalk post for more usage info
SO 相关主题:
这个说不可能,但用户也想要一个用例,我希望我已经提供了。 How to obtain an object from a string?
其他: When is the output of repr useful? How to print a class or objects of class using print()? Allowing the repr() of my class's instances to be parsed by eval() Main purpose of __repr__ in python how do you obtain the address of an instance after overriding the __str__ method in python Python repr for classes how to use 'pickle'
【问题讨论】: