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?
Yes it does. That’s what
Ape()does: it creates an newApeobject, and as part of that process the__init__method gets run.In your example, you then call the
saymethod of that object. Note that there would be no way to callsayif you didn’t have anApeobject.