Hadriscus
Hadriscus

Reputation: 129

How to connect attributes from list when Maya does not find those attributes?

What I am looking to do is batch connect attributes from object A to object B. Just the transform attributes, so, I did this:

import maya.cmds as mc

sel = mc.ls(sl=True)

mc.connectAttr(sel[0]+'.t', sel[1]+'.t')
mc.connectAttr(sel[0]+'.r', sel[1]+'.r')
mc.connectAttr(sel[0]+'.s', sel[1]+'.s')

And then I thought it would be more clever if I created a list containing (translate, rotate and scale) and just iterate over that list instead of specifying ".t", ".r" and ".s".

So I did this:

import maya.cmds as mc

sel = mc.ls(sl=True)
attributes = ['.t', '.r', '.s']

for attr in attributes :
    mc.connectAttr(sel[0].attr, sel[1].attr)

...to which the console says

# Error: AttributeError: file <maya console> line 7: 'unicode' object has no attribute 'attr' # 

I did some searching, but it didn’t help me understand. Can someone explain why this is happening, and how I can achieve the desired results?

Upvotes: 1

Views: 1150

Answers (1)

Wrzlprmft
Wrzlprmft

Reputation: 4434

Your last line has to be:

mc.connectAttr(sel[0]+attr, sel[1]+attr)

You are using . as if it were the string concatenation error in Python, while + is.

Instead . is the attribute operator, which explains your error¹. When Python tries to interpret sel[0].attr, it first notes that sel[0] is a unicode object and then tries to get the attribute attr from that object. This attribute has nothing to do with the attr from your loop and in particular doesn’t exist. Hence the error message you got.


¹ Every object in Python has some attributes, which you can access with that syntax and which depend on the type object. To get familiar with this try:

a = 42
print(a.numerator)
print(a.denominator)

print(a.wrzlprmft)
# Raises AttributeError. This is what happened to you.

print(denominator)
# Raises NameError.
# This demonstrates that denominator is only defined as an attribute of a.

Upvotes: 2

Related Questions