0

I have the below code base:

from datetime import datetime
from operator import attrgetter

class Person:
    def __init__(self,name,day,month,year):
        self.name = name
        self.day = day
        self.mon = month
        self.year = year

    def __str__(self):
        if self.day < 10:
            day = "0" + str(self.day)
        else:
            day = str(self.day)
        if self.mon < 10:
            mon = "0" + str(self.mon)
        else:
            mon = str(self.mon)
        display = day + "-" + mon + "-" + str(self.year)
        return display

    def __repr__(self):
        if self.day < 10:
            day = "0" + str(self.day)
        else:
            day = str(self.day)
        if self.mon < 10:
            mon = "0" + str(self.mon)
        else:
            mon = str(self.mon)
        display = day + "-" + mon + "-" + str(self.year)
        return display

def sortdates(l1):
    for dates in l1:
        dates.finalbirthdate = datetime.strptime(repr(dates),"%d-%m-%Y")
    return sorted (l1,key=attrgetter('finalbirthdate'),reverse=True)

if __name__ == '__main__':
    p1 = Person("Subhayan",18,9,1984)
    p2 = Person("Poulomi",13,1,1988)
    p3 = Person("Dummy",13,1,1988)
    p4 = Person("Shaayan",25,11,1988)
    p5 = Person("Father",1,1,1954)

    check = sortdates([p1,p2,p3,p4,p5])
    for persons in check:
        print (persons)

Now the main purpose of the sortdates function was to sort the objects based on finalbirthdate attribute.

But what if i want to find out unique in that list based on the value of finalbirthdate attribute.

So for instance both "Poulomi" and "dummy" objects have the same finalbirthdate attribute so i want to take only one of them and not two .

Is there a way to do this ?

Thanks in advance.

tdelaney
  • 73,364
  • 6
  • 83
  • 116
Subhayan Bhattacharya
  • 5,407
  • 7
  • 42
  • 60
  • Can't you take the `set()` of the relevant list? –  Apr 11 '17 at 06:37
  • 1
    Possible duplicate of [Elegant ways to support equivalence ("equality") in Python classes](http://stackoverflow.com/questions/390250/elegant-ways-to-support-equivalence-equality-in-python-classes) – Steven Summers Apr 11 '17 at 06:47
  • Is i take set how will i make it to take unique based on the finalbirthdate attribute only ? The name attribute would anyways be different. – Subhayan Bhattacharya Apr 11 '17 at 07:15

1 Answers1

0

Add these methods to the class

def __eq__(self, other):
    return self.day == other.day and self.mon == other.mon and self.year == other.year

def __hash__(self):
    return hash(self.__str__())

and change check = sortdates([p1,p2,p3,p4,p5]) to

check = sortdates(set([p1,p2,p3,p4,p5]))
Himaprasoon
  • 2,609
  • 3
  • 25
  • 46