【问题标题】:How to create an object of an instance from string in Python如何在 Python 中从字符串创建实例的对象
【发布时间】: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'

【问题讨论】:

    标签: python eval maya repr


    【解决方案1】:

    要使eval 工作,需要覆盖内置的__repr__ 函数。我没有看到你提到这一点,所以我认为你没有这样做。我正在粘贴我不久前写的代码 sn-p。只是为了演示。在此示例中,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/

    【讨论】:

    • 看起来这会创建一个 new 实例,而不是调用 existing 实例的方法
    • 认为我刚刚找到了一种实际使用 id 而不是 rep 字符串的方法。 stackoverflow.com/a/15702647/1495017 将完全实施,看看我是否遇到任何问题。
    • @PaulLohman,我只是在测试同样的东西。效果很好
    • 哇,就这样使用它; command = ("python(\"ctypes.cast(%s,ctypes.py_object).value.thing=False\")")%(id(self)) nameCommand = cmds.nameCommand('setThingOnPress', annotation=' ', 命令=命令)
    • @PaulLohman,您应该将其作为新答案发布并接受。这样未来的访问者可以看到并从中学习。确保还包含指向您找到的其他有价值答案的链接
    【解决方案2】:

    找到了一个似乎对我有用的方法here 使用 id 作为字符串和 ctypes

    class Foo:
        pass
    
    f = Foo()
    f.thing = 'Jeff'
    
    import ctypes    
    long_f = id(f)
    y = ctypes.cast(long_f,ctypes.py_object).value
    name = y.thing
    

    这里是 Maya 中的一个示例用法;

    command = ("python(\"ctypes.cast(%s,ctypes.py_object).value.thing=False\")")%(id(self))
    nameCommand = cmds.nameCommand( 'setThingOnPress', annotation='', command=command )
    cmds.hotkey( keyShortcut='b', name=nameCommand)
    

    【讨论】:

      猜你喜欢
      • 2013-06-15
      • 2015-08-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 2017-03-15
      相关资源
      最近更新 更多