Python: calls the method "directly", instantiating an object?

I'm new to Python, and while the module was testing some methods on my object, I noticed something strange.

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 small example to illustrate where I got confused. If you do Ape (). Say ('eeek') does this actually make an instance of the Ape object and invoke the init method? I thought it wouldn't be, but I had some weird side effects, so now I think it is?

+7
python
source share
3 answers

Yes Yes. What Ape() does: it creates a new Ape object, and as part of this process, the __init__ method is launched.

In your example, you call the say method of this object. Note that there would be no way to call say if you did not have an Ape object.

+10
source share

If you want to directly call a method without instantiating, you can use the staticmethod decorator. Please note that when using the static method

no self
 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 class is the first parameter instead of 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() 
+12
source share

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

To be clear:

 Ape().say('eeek') 

equivalent to:

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

Which more clearly indicates what happens first.

+3
source share

All Articles