Adding methods dynamically to MObject in python

maya
coding
python

#1

Hey there,

We’ve written a few classes to serialize various objects, one way we’re thinking of handling this is by adding a ‘special’ method to the classes we want to write out.

We’ve managed to do this with motionbuilder thanks to python’s flexibility, however we’re unable to add methods to any maya.api.OpenMaya classes:

def my_method(self):
    return 'my_method'
maya.api.OpenMaya.MObject.my_method = my_method

# Error: TypeError: file <maya console> line 1: can't set attributes of built-in/extension type 'OpenMaya.MObject' # 

This is the case for almost all maya.api classes. Has anyone gotten around this?


#2

As it says, you can’t actually add methods to builtin objects, so there isn’t really a way to add them.
These objects were defined in C and as such lack much of flexibility you’d get from a python defined object.

You could always create a subclass that holds your extra methods.
Or instead just create them as functions where you pass the objects in explicitly.


#3

Thanks for the confirmation.