I have a python code roughly like this:
class SomeClass():
def get_date(self):
date = # read the data from the database in YYYY-MM-DD HH:MM:SS format
return date
now, I will use the returned value in an API query, which accepts the input as a unix timestamp. Actually I can give the returned date to another function to have it converted to a timestamp, but I thought it would be a good opportunity to learn about function cascading / chaining, which I've always wondered about in Python.
Now, what I basically want to achieve is something like this:
- If I just execute
SomeClass.get_date(), I want to have the date in the same format that has been returned from the database, which is YYYY-MM-DD HH:MM:SS - If I execute
SomeClass.get_date().as_timestamp(), I should get it as timestamp. - If not possible, I would settle for having it like
SomeClass.get_date().as_datetime()andSomeClass.get_date().as_timestamp() - I might use the second function (
.as_timestamp()) for more than one primary function (there are multiple datetime columns that I may need to be converted into timestamp).
I've looked into some examples of function cascading. They are mostly saying that key to this is returning the self, but I could not find any info about how to implement it in the way I need to.
I basically need the return value to be fed into the second function (I guess), but not sure if it is possible, and don't know how to do it. Any ideas?
get_dateis going to have to return some object that has the rest of the methods you want to use. You could have the__str__of the Date object use the default representation, then have each of the other methods return other specific formatting.Noneto emphasize that the object is being mutated (if the method doesn't return anything, why else you be calling it?). What you want to do is simply invoke a method on the return value of another method without using a temporary variable to store an intermediate value.