gpt4 book ai didi

python - 如何在 Python 中从字符串创建实例的对象

转载 作者:太空宇宙 更新时间:2023-11-04 01:19:55 26 4
gpt4 key购买 nike

我在 Maya 中使用 Python 2.5 编写动态热键管理器类,在尝试分配特定于实例的命令时遇到了麻烦,因为 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'

最佳答案

要使 eval 起作用,需要覆盖内置的 __repr__ 函数。我没有看到你提到这一点,所以我认为你没有这样做。我正在粘贴我前一段时间写的代码片段。只是为了演示。在此示例中,eval 起作用是因为 __repr__ 被覆盖了:

class element :
def __init__(self, a, m):
self.name = a ;
self.atomic_mass = m ;

def __str__(self):
return "{0} has atomic mass {1}".format(self.name, self.atomic_mass)

def __repr__(self):
return "element(\"{0}\", \"{1}\")".format(self.name, self.atomic_mass)

H = element("Hydrogen", 1.00794)
print H
print repr(H)
print eval(repr(H))

更多信息:http://www.muqube.com/python/string-representation-of-python-objects/

关于python - 如何在 Python 中从字符串创建实例的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21925194/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com