Search code examples
pythonclassmaya

Maya Python call modul class functions


Hey I want to understand the process of importing and reloading scripts with Python in Maya.

I have the following code that throws following error:

# NameError: name 'MyClass' is not defined #

It creates the window but when I press the button it gives me the error above. Would be great if someone could help me what I am missing here.

import maya.cmds as cmds
from functools import partial

class MyClass():

    @classmethod
    def createWindow(cls):

        windowID = 'window'

        if cmds.window(windowID, exists = True):
             cmds.deleteUI('window')

        window = cmds.window(windowID, title="Blast", iconName='Blast', widthHeight=(400, 200) )
        cmds.frameLayout( label='')

        cmds.button( label='Playblast' ,command= 'MyClass.createPlayblast()')

        cmds.showWindow( window )

    @classmethod
    def createPlayblast(cls):

        cmds.playblast( f= "playblast", fmt= "image")
        print "hallo"

MyClass.createWindow()

I am calling my modul like this:

# call loadTest

import sys
Dir = 'S:/people/Jan-Philipp/python_scripts'
if Dir not in sys.path:
sys.path.append(Dir)
try: reload(loadTest)
except: from loadTest import MyClass

loadTest.MyClass()

Cheers, hope you all have a nice day!


Solution

  • You probably want to remove MyClass.createWindow() from the window, and leave that to the calling code. As written it will create a window every time you import the module. It's better to put only initialization code into the module scope.

    The problem in this case is that you're trying to call the class as if it were a function. If you only want classmethod, you'd do it like this

    import loadTest
    
    loadTest.MyClass.createWindow()
    

    In Python we generally don't need to do make classes which only have class methods: A module is usually what you'd use. In this case:

    import maya.cmds as cmds
    from functools import partial
    
    def createWindow():
    
        windowID = 'window'
    
        if cmds.window(windowID, exists = True):
             cmds.deleteUI('window')
    
        window = cmds.window(windowID, title="Blast", iconName='Blast', widthHeight=(400, 200) )
        cmds.frameLayout( label='')
    
        cmds.button( label='Playblast' ,command= createPlayblast)
    
        cmds.showWindow( window )
    
    def createPlayblast():
    
        cmds.playblast( f= "playblast", fmt= "image")
        print "hallo"
    

    and

    import loadTest
    loadTest.createWindow()
    

    A module is a better tool for grouping related functions than a class. Classes only make sense in Python if the class contains some persistent data.