【问题标题】:super function doesn't work inside a maya python module超级函数在 Maya python 模块中不起作用
【发布时间】:2011-02-17 23:27:39
【问题描述】:

不知何故,这在 Maya/Python 脚本编辑器中运行良好,但在我的模块代码中时会失败。有人有什么想法吗?

class ControlShape(object):
    def __init__(self, *args, **kwargs):
        print 'Inside ControlShape...'

class Cross(ControlShape):
    def __init__(self, *args, **kwargs):
        print 'Entering Cross...'
        super(Cross, self).__init__(*args, **kwargs)
        print 'Leaving Cross...'

x = Cross()

这给了我一个 TypeError: super(type, obj): obj must be an instance or subtype of type.

【问题讨论】:

  • 粘贴到 ipython 中没有任何错误,确定你的程序中没有其他代码?
  • 完整的回溯会很有帮助。此代码也适用于 CPython 2.6.5。
  • 是的,问题是它在 Maya 模块中不起作用,我不明白。
  • 错误消息暗示self 不是Cross 的实例。有什么东西会反弹Cross吗?也许在您的代码或 Maya 中发生了一些事情,它用某种包装器替换了绑定到类的名称?完整的回溯会有所帮助:如果 Cross 确实是实际类的某种包装器,那么它应该显示在堆栈中。

标签: python class maya


【解决方案1】:

我遇到了同样的问题。每次进行更改时重新启动 Maya 绝对不切实际。我找到了一个answer here 为我解决了这个问题。

您应该阅读链接的答案以了解为什么它只适合调试。但简单来说,将这段代码放在 userSetup.py 中,然后每次编辑代码时运行 reload_package(my_package)

import sys, types
def reload_package(root_module):
    package_name = root_module.__name__

    # get a reference to each loaded module
    loaded_package_modules = dict([
        (key, value) for key, value in sys.modules.items() 
        if key.startswith(package_name) and isinstance(value, types.ModuleType)])

    # delete references to these loaded modules from sys.modules
    for key in loaded_package_modules:
        del sys.modules[key]

    # load each of the modules again; 
    # make old modules share state with new modules
    for key in loaded_package_modules:
        print 'loading %s' % key
        newmodule = __import__(key)
        oldmodule = loaded_package_modules[key]
        oldmodule.__dict__.clear()
        oldmodule.__dict__.update(newmodule.__dict__)

【讨论】:

  • 有没有办法把 ipython 的自动重载挂到这个上?否则必须在使用 super 更改包中的行时重新启动内核
  • 即使 ipython 中的 %autoreload 2 不起作用,也可以使用,抛出 TypeError: super(type, obj): obj must be an instance or subtype of type `
【解决方案2】:

这与重新加载模块有关。重新加载模块经常会改变内存中的内部对象,这使得 super 的 isinstance 测试返回 False。

http://thingspython.wordpress.com/2010/09/27/another-super-wrinkle-raising-typeerror/

【讨论】:

  • 你刚刚拯救了我的一天。我的代码用于需要较长正常运行时间的守护程序,并且使用了重新加载模块,在感谢您的回答之前我并不知道。显然,我们需要比这个可怜的 hack 更可靠的东西。
  • 我经常使用 ipython 的自动重载功能发生这种情况
【解决方案3】:

原来它与我在模块顶部的导入有关。不过我忘记是哪一个了。我应该在我发现它的那一刻就发布这个。

【讨论】:

    【解决方案4】:

    如果您使用总是这样称呼它的 super(Class, self).__init__,这是一个很好的经验法则。这适用于从对象继承的类。

    class ControlShape(object):
       def __init__(self, *args, **kwargs):
          super(ControlShape, self).__init__()
          print 'Inside ControlShape...'
    

    看看这是否能解决你的错误。只是猜测,因为我不使用 Maya,但值得一试。

    【讨论】:

      猜你喜欢
      • 2022-07-01
      • 2011-11-18
      • 2011-09-30
      • 1970-01-01
      • 2018-09-29
      • 1970-01-01
      • 1970-01-01
      • 2021-06-25
      • 1970-01-01
      相关资源
      最近更新 更多