To get a better understanding of how classes are called and work, I have been trying to take a handful of functions that have been working for me in a simple script I have written that snaps one object to another in 3D space in maya.
When I put them in a class and try to run the code, the error message that I got was:
Error: NameError: file line 10: global name 'runSelected' is not defined #
I thought that this might be because I was calling methods that did not have self.
in front of them. I tried doing this though and am still getting an error which is:
Error: NameError: file line 35: global name 'self' is not defined #
The script is run after selecting two objects in 3D space in maya and kicked off by running:
Align()
The code for the class is below:
#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()
When defining instance method you need to explicitly pass self
as a first parameter of a method. For example def runSelected(object):
should be changed to def runSelected(self, object):
, only then you can access self
in method body. You should read up on python self
and instance methods to gain some intuition.