Reputation: 3
I've created a class, and I am unsure how to approach the following problem. Is it possible to create a function that will be able to do what is in the example? (For practical uses, I would be comparing dates and returning true if the day and month are the same but not necessarily the years are the same)
Example:
>>>strvar1 = 'abc-123'
>>>strvar2 = 'abc-456'
>>>strvar1.myfunction(strvar2)
True
Class code
class Date(object):
def __init__(self, x0 = 1900, y0 = 1, z0 = 1):
self.x = x0
self.y = y0
self.z = z0
def __str__(self):
date = str(self.x) + "-" + str(self.y).rjust(2, '0') + "-" + str(self.z).rjust(2, '0')
return date
def myFunction(j):
So with the example it would look like:
d1 = Date(1999, 1, 1) //d1 = "1999-01-01"
d2 = Date(2000, 2, 2) //d2 = "2000-02-02"
d3 = Date(2001, 2, 2) //d3 = "2001-02-02"
>>>d1.myFunction(d2)
False
>>>d2.myFuction(d3)
True
Upvotes: 0
Views: 80
Reputation: 77099
There's nothing wrong with a class-based approach, but functional programming has a solution for this too, in partial functions:
def make_has_same_month_day(d1):
"""return a function that takes a date
and returns true if the month and day are the same as the enclosed date"""
def has_same_month_day(d2):
return d1.y == d2.y and d1.z == d2.z
return has_same_month_day
This can also be written using functools.partial
.
from functools import partial
def same_month_day(d1, d2):
"""return true if both dates have the same month and day"""
return d1.y == d2.y and d1.z == d2.z
has_same_month_day = partial(same_month_day, d1)
Upvotes: 0
Reputation:
Yes absolutely, this is a reason for having classes. Read up on https://docs.python.org/2/tutorial/classes.html.
def myFunction(self, cdate):
return self.y == cdate.y and self.z == cdate.z
Upvotes: 1
Reputation: 381
If you are trying to perform a comparison before method invocation you could use the ternary operator to evaluate a condition then return the variable you want. An example is listed below written in JavaScript
var a = 1
var b = 2
myObj.myMethod( (a>b) ? a : b );
In the above example the ternary syntax
(a>b) ? a : b
will evaluate a is greater than b then return a if true otherwise if a is less than b it will return b.
Without knowing language you may want to check out the wiki page for your languages particular syntactical implementation.
Upvotes: 0