Setting object attributes in Maya with Python

How to set attributes on objects in Maya using Python scripting.

Let’s take a look at how we would do this, firstly we’ll set up our script by importing the maya commands library:

from maya import cmds

And we’ll create a cube object:

cube = cmds.polyCube()

Before we move on we need to get the object name, if we print the cube variable we’ll get the following output:

[u'pCube1', u'polyCube1']

While this list can be useful, it’s not really what we want in this case, we only need the ‘pCube1’ bit, as we’ll use this name to apply the attributes in a moment.

Let’s create another variable, and in it we will store the object name:

cubeShape = cube[0]

If we print this new variable, we’ll get the output we need:

pCube1

If we were to change our variable query to:

cubeShape = cube[1]

The output would be ‘polyCube1’, as this is 2nd in the object list.


We can now use this to build our command to set an attribute, for this example lets lock all 3 translate values (X, Y and Z), essentially resulting in a cube object you can’t move.

cmds.setAttr(cubeshape+".translate", lock=True)

Let’s break this command down, see what’s going on:

  • cmds = From the maya commands library
  • .setAttr() = Get the .setAttr method
  • cubeShape = We’ve stored our object name in this already (pCube1)
  • +”.translate” = This is the attribute are we modifying
  • , lock=True = This is the new value of the attribute

The final code

# Import maya commands library
from maya import cmds

# Create a cube object
cube = cmds.polyCube()

# This will output a list [u'pCube1', u'polyCube1']
print cube

# Get the cube shape from the cube object
cubeshape = cube[0]

# This will output pCube1
print cubeshape

# Lock the translate attrubute
cmds.setAttr(cubeshape+".translate", lock=True)