I have a Sleep class (object) and within that class a sleepInSeconds() method.
Is there any difference between doing this:
wait = Sleep()
wait.sleepInSeconds(10)
And doing this:
wait = Sleep().sleepInSeconds(10)
or
Sleep().sleepInSeconds(10)
Which is more correct (or 'Pythonic'), what kinds of problems could I run into with one or the other? Is there some overarching principal from OO programming that should have led me to this answer?
4 Answers 4
If sleepInSeconds is a static method (seen from a functional point of view) you are misusing the sleep class as a namespace. Sounds a bit like a java background.
You could perhaps better make sleepInSeconds a function in the module namespace (not in a class) as python has very good namespace support.
If you still want to have it in a class, and the method does not use instance variables (fron self) then you could annotate that method as static (@staticmethod) and you should then use the class name, and not the instance, yo make explicit that it is a static method which does not change your instance's state.
So both you options seem somehow not pythonic to me.
If sleepInSeconds does change the instance state then I'd go for wait.sleepInSeconds(10) as you probably need the changed state somewhere.
2 Comments
wait = sleep()
wait.sleepInSeconds(10)
and
wait = sleep().sleepInSeconds(10)
Have entirely different outcome. In this first case wait reference to a sleep instance. In the second case wait reference to the return value of sleepInSeconds. You need to figure out what you are trying to get. Either case is Pythonic. They question is what are you expecting wait to be.
Comments
All three are functionally correct. The main difference is what you intend to do after this bit of code.
wait = sleep()
wait.sleepInSeconds(10)
The above code will leave you a sleep object hanging around afterwards, under the name wait. If you intend to use this object more or later, you probably want this.
wait = sleep().sleepInSeconds(10)
The above will put the return value of sleepInSeconds() to wait. In some cases, this may be None. It could be an integer, too. Note, you can have sleepInSeconds() return self, in which case it is functionally equivalent to the first block.
sleep().sleepInSeconds(10)
The above will just sleep for 10 seconds. There will be no sleep object left over. Use this if you never want to use the object again.
In my opinion, the most Pythonic are the first and last one. Use the first one if you want to keep the object around, and the second one if you don't need the object later.
1 Comment
Unless you want to reuse your instance of sleep, keeping it around is a waste (allocating wait). Don't jam too much stuff on one line.
The truer Pythonic style is to just use the libraries :P
import time
time.sleep(seconds)
2 Comments
sleepInSeconds() is telling the current thread to wait? Perhaps it's telling a monster to go to sleep in some game. :-)