PDA

View Full Version : commands within classes/instances


Soviut
01-20-2008, 10:41 PM
I'm trying to wrap a button control in a class. I want the button's command to call an instance method, but it seems the command string doesn't like when I try to use "self".


import maya.cmds as cmds
class buttonWrapper():
def __init__(self):
cmds.button("wrappedButton", command="self.onClick()")

def onClick(self);
print "clicked!"
return


I get the following error

# NameError: name 'self' is not defined #

So it seems I can't use instance methods in button (and other control) commands? Is there any possible alternative?

Gravedigger
01-20-2008, 10:48 PM
maybe you need to use 'this' instead of 'self'?

Soviut
01-20-2008, 11:32 PM
"this" is not a Python keyword. I gave it a try, just incase its some Python-to-MEL transition thing. Nonetheless, it didn't work either.

Gravedigger
01-21-2008, 12:03 AM
hmm..i've already feared that

sorry just gave an idea. i don't know phyton. just c++

katisss
01-21-2008, 09:15 AM
class buttonWrapper():
def __init__(self):
cmds.button("wrappedButton", command="self.onClick()")

def buttonWrapperonClick(self):
print "clicked!"
return

gives me no errors. Did you make sure it wasnt the ";" insteasd of a ":" after the buttonWrapperonClick(self)?

Soviut
01-21-2008, 03:40 PM
Sorry, my example isn't really in context. That command will only fire when the button is clicked, that's why no error occurs when you just run the code. Its a NameError at runtime, not compile time.

I'm sure it wasn't a semi-colon issue because if it was I would have given me a SyntaxError at compile time, long before the code had a chance to run.

Soviut
01-21-2008, 03:54 PM
Doh, I solved it. It was because of how I was passing the command in. In Python it turns out you don't need to pass as a command string anymore, you can pass an actual function pointer. I was careless and was passing the actual function result because I included parentheses at the end of the command.

Below is the code that works. Notice there's an *args arguement in the onClick() method. This is because optional arguements can be sent, but if none are present then it just sends an empty string, so it has to be there.


import maya.cmds as cmds
class buttonWrapper():
def __init__(self):
cmds.button("wrappedButton", command=self.onClick)

def onClick(self, *args):
print "clicked!"
return

CGTalk Moderation
01-21-2008, 03:54 PM
This thread has been automatically closed as it remained inactive for 12 months. If you wish to continue the discussion, please create a new thread in the appropriate forum.