首页 > 解决方案 > 如何在 Python 中为 Maya 脚本修复一个简单类中的未定义方法?

问题描述

为了更好地理解类是如何被调用和工作的,我一直在尝试在我编写的一个简单脚本中使用一些对我有用的函数,该脚本在 Maya 的 3D 空间中将一个对象捕捉到另一个对象。

当我将它们放在一个类中并尝试运行代码时,我得到的错误消息是:

错误:NameError:文件第 10 行:未定义全局名称“runSelected”#

我认为这可能是因为我正在调用self.前面没有的方法。我试过这样做,但仍然收到一个错误,即:

错误:NameError:文件第 35 行:未定义全局名称“self”#

该脚本在 Maya 中选择 3D 空间中的两个对象后运行,并通过运行启动:

Align()

该类的代码如下:

#Class for snapping one object to another in Maya.

import maya.cmds as mc


class Align(object):

    def __init__(self):
        #starts the runSelected Method
        self.runSelected()       

    def selectionCheck(mySel):
        #checks that 2 ojects are created, returns True if so, Flase if not.
        if len(mySel) == 2:   
           print "Great! Two selected"  
           return True

        elif len(mySel) == 0: 
           print "Nothing Selected to constrain!"
           return False   

    def createWindow():
        #This creates a simple dialogue window that gives a message.
        mc.confirmDialog(title='Align Objects', m ="Instructions: You need to select two objects to constrain.")

    def runConstrainDelete(mySel):
        #Creates a parent constraint, does not maintain offset and then deletes the constraint when object is moved.Clears selection.
        myParentConstraint = mc.parentConstraint(mySel[0], mySel[1], mo=False)
        mc.delete(myParentConstraint)
        mc.select (clear=True)

    def runSelected(object):
        #Creates a list of objects selected. Runs selection check
        mySel = mc.ls(sl =True)
        result_Sel_Check = self.selectionCheck(mySel)

        #if statement handles if a warning window or the rest of the script should be run.
        if result_Sel_Check == False:
            self.createWindow()    
        else:
            self.runConstrainDelete(mySel)


test_Align = Align()

标签: pythonmaya

解决方案


定义实例方法时,您需要显式传递self方法的第一个参数。比如def runSelected(object): 应该改成def runSelected(self, object):,才可以self在方法体中访问。您应该阅读 pythonself和实例方法以获得一些直觉。


推荐阅读