[Maya Python] Object's Only Created When Applied To A Variable

Hello,

I’m taking my first steps into looking at Python’s modules and classes and how to create custom ones for Maya. I’ve created a basic class which creates a sphere and if you type:

s = MayaSphere(name="Sphere")

it will be created in the viewport, similarly it will be created if appended to a list:

sphereList = []
sphereList.append(MayaSphere(name="Sphere"))

but it won’t be created if you type

MayaSphere(name="Sphere")

What happens instead is that the memory location is returned, but nothing appears in the viewport. Can someone explain why this happens?

Thanks,
-Harry

In order to be able to call a class method directly, you need to make it a static method. Other wise you’ll need an instance the class.

class mysphere(object):
    def __init__(self, *args, **kwargs):
        super(mysphere, self).__init__(*args, **kwargs)
    
    @staticmethod
    def makesphere():
        return pm.sphere()
        
l = []
l.append(mysphere.makesphere())

Alternatively, you can store the method without executing too by omitting the () part.

mylist = [ mysphere.makesphere ]

Now you can executing it by doing this. Pretty useful for automating your script.

mylist[1]()

So without actually seeing your code I can’t comment as to why the sphere wouldn’t be created in the viewport.

But I do want to say, that classmethods exist in python, and are often preferred over staticmethods. The reasoning is that if at some point in the future you need a reference to the class object, you have it, and if you don’t need that reference you can easily ignore it.

In general you can just use a function instead of a staticmethod, python is really flexible like that, not everything needs to be attached to an object.

From your description it sounds like your class creates the sphere as a side effect of its initialization. That’s why you get a memory location as the printout for creating the class – you’re creating the class alright, and that’s what comes back from the simple call (check the contents of your list: they should also be class instances with memory locations)

In general, you should be careful about creating things as side effects: at the very least you should make it clear (with your documentation and names and idioms) whether making a MayaSphere or whatever is just creating a data structure or actually changing the scene – otherwise somebody using your code might make a new MayaSphere() to get at some method on the class without realizing that they’ve also changed the scene. You can create classes which are explicitly bound to scene objects but you should make it obvious that creating them changes the scene (and ideally you should make them clean up after themselves)