Maya’s python interface leaves something to be desired, as it seems like a straight port of their existing MEL interface with no additional thought put into designing a nice OO interface. For example, here is how to set or get the ‘radius’ attribute of a sphere:
s = cmds.sphere() r = cmds.sphere(s, query=True, radius=True) cmds.sphere(s, edit=True, radius=10)
Nasty.
So, here is a wrapper to make things nicer:
import maya.cmds as cmds class Wrapper(object): def __init__(self, other): self.__dict__['me'] = other() def __getattr__(self, thing): i = 0 if cmds.attributeQuery(thing, node=self.__dict__['me'][0], exists=True) else 1 return cmds.getAttr(self.__dict__['me'][i] + "." + thing) def __setattr__(self, thing, value): i = 0 if cmds.attributeQuery(thing, node=self.__dict__['me'][0], exists=True) else 1 cmds.setAttr(self.__dict__['me'][i] + "." + name, value)
The above example is now:
s = Wrapper(cmds.sphere) r = s.radius s.radius = 10
Comments 2
Nice trick, but your comparison is not really fair. Your negative example is using the “sphere” command to get and set the radius attribute. Then, your code is little more than a string substitution into the setAttr and getAttr commands. Nice use of Python, by the way, but not a substitution for the “sphere” command. The actual Maya.cmds example that you are addressing is:
I’m not criticizing your skills at all. I’ve just had to diffuse a few viral e-mail threads at my studio claiming your Wrapper class is some sort of object-oriented Maya.cmds wrapper, when it only wraps setAttr and getAttr.
Posted 08 Aug 2009 at 10:10 am ¶Yes, I never meant it to be more than an easier, or ‘more natural’ syntax-hack for those coming from Python. That’s why I named it “Wrapper”!
For what it’s worth, I ended up extending this to be a little bit smarter… for one thing this short example only affects the first object in the array returned by
cmds.sphere. However, I don’t seem to have kept it (I just cooked it up for a short Uni project).Thanks for your comments
Posted 09 Aug 2009 at 9:59 pm ¶Post a Comment