Problem in using maya command expression.

243 views
Skip to first unread message

lov2soul

unread,
Aug 13, 2014, 3:08:06 AM8/13/14
to python_in...@googlegroups.com
Hello everyone,

I am trying to using maya command expression. but i get Error message. 


please help.

Code is:

import maya.cmds as cmds
from functools import partial

class TestClass(object):     
    def __init__(self, *args):
    pass

    def testFunction(self):
    print "testFunction"

    def expFunction(self):

        #self.testFunction() # no error

    #cmds.expression( s= 'self.testFunction' ) # error: canot find procedure "self.testFunction"

    #cmds.expression( s = 'python("(self.testFunction)")')  #error : name 'self' is not defined

        cmds.expression( s = 'python("partial(self.testFunction)")')  #error : name 'self' is not defined


test = TestClass()
test.expFunction()


is this possible use callback testFunction using expression?

Thanks in advance!

Jesse Kretschmer

unread,
Aug 13, 2014, 10:56:43 AM8/13/14
to python_in...@googlegroups.com
You are changing scopes, so your "self" variable is no longer available.

When you call cmds.expression() and python(), the code will be executed in the global namespace. In order to access your object you'll need to reference it from the global object name. If you are running this from the script editor, your object would be named "test". So the quick fix is to change the expression from self.testFunction to test.testFunction.

Hopefully this has tweaked your spidey senses. Hardcoding an object instance name into the method will be difficult to maintain, and difficult to re-use. 

Expressions can be multi-line strings. You may be able to find a way to create your object within the expression and then call that method from that object.

This example should work from the script editor(untested):

import maya.cmds as cmds
from functools import partial

class TestClass(object):
     
    def testFunction(self):
        print "testFunction"

myExpression = """
myTestObject = TestClass()
myTestObject.testFunction()
"""

cmds.expression( s = myExpression )

It might help to describe your overall goal. This example is not robust as it needs the TestClass to be defined in the global scope. If you ever want to put that class code into a module the expression would no longer be able to address it.

Best of luck,
Jesse


Reply all
Reply to author
Forward
0 new messages