Pickels
Pickels

Reputation: 34630

Python: does calling a method 'directly' instantiate the object?

I am new to Python and while unit testing some methods on my object I noticed something 'weird'.

class Ape(object):
    def __init__(self):
        print 'ooook'

    def say(self, s):
        print s

def main():
    Ape().say('eeek')

if __name__ == '__main__':
    main()

I wrote this little example to illustrate where I got confused. If you do Ape().say('eeek') does this actually instantiate an Ape object and run the init method? I thought it wouldn't but I had some weird side effects so now I am thinking it does?

Upvotes: 8

Views: 5760

Answers (3)

John La Rooy
John La Rooy

Reputation: 304147

If you want to call a method directly without creating an instance you can use the staticmethod decorator. Notice that there is no self when you use a static method

class Ape(object):
    def __init__(self):
        print 'ooook'

    @staticmethod
    def say(s):
        print s

def main():
    Ape.say('eeek')

if __name__ == '__main__':
    main()

Compare with class methods where the class is the first parameter instead of an instance

class Ape(object):
    def __init__(self):
        print 'ooook'

    @classmethod
    def say(cls, s):
        print "the class is:", cls
        print s

def main():
    Ape.say('eeek')

if __name__ == '__main__':
    main()

Upvotes: 14

apalopohapa
apalopohapa

Reputation: 5183

Yes. Ape() instantiates an object of class Ape, although since there is no assignment, no label is associated with it. At this point its __init__ function is called. Then, the say function is called.

To be clear:

Ape().say('eeek')

is equivalent to:

(Ape()).say('eeek')

Which more clearly indicates what happens first.

Upvotes: 3

David Z
David Z

Reputation: 131560

Yes it does. That's what Ape() does: it creates an new Ape object, and as part of that process the __init__ method gets run.

In your example, you then call the say method of that object. Note that there would be no way to call say if you didn't have an Ape object.

Upvotes: 12

Related Questions