Pythonオブジェクト比較

2340 ワード

class Myobject(object):
    def __init__(self, val):
        self.val = val

    def __eq__(self,other):
        return self.val == other.val

    def __gt__(self,other):
        return self.val > other.val

a = Myobject(1)
c = Myobject(3)
b = Myobject(2)

print(a>b, a==b, a<b)

l = [a, c, b]
for myob in l:
    print(myob.val)

l.sort()
for myob in l:
    print(myob.val)

 
 
# python 2
import functools

@functools.total_ordering
class Myobject(object):
    def __init__(self, val):
        self.val = val

    def __eq__(self,other):
        return self.val == other.val

    def __gt__(self,other):
        return self.val > other.val

a = Myobject(1)
c = Myobject(3)
b = Myobject(2)

print(a>b, a==b, a<b)

l = [a, c, b]
for myobject in l:
    print(myobject.val)

l.sort()
for myobject in l:
    print(myobject.val)

 
 
from collections import namedtuple
from operator import itemgetter

Person=namedtuple("Person",'name age email')

f = Person('wow',3,'[email protected]')
p = Person('tom',44,'[email protected]')
o = Person('mary',10,'[email protected]')
o2 = Person('jimi',10,'[email protected]')
plist = [f, p, o, o2]

#   age   
sp = sorted(plist, key=lambda x:x.age)
for p in sp:
    print p
#     
sp = sorted(plist, key=itemgetter(1,0))
for p in sp:
    print p

しゅつりょく
Person(name='wow', age=3, email='[email protected]')Person(name='mary', age=10, email='[email protected]')Person(name='jimi', age=10, email='[email protected]')Person(name='tom', age=44, email='[email protected]')
Person(name='wow', age=3, email='[email protected]')Person(name='jimi', age=10, email='[email protected]')Person(name='mary', age=10, email='[email protected]')Person(name='tom', age=44, email='[email protected]')