I have a dictionary of the following form:
{ <Category('Simulate', 'False', 'False', 'False', 'INTERMEDIATE')>: {'link': u'/story/4/tvb-adapters-simulator-simulatorAdapter/SimulatorAdapter', 'name': u'Simulate'},
<Category('View Results', 'True', 'False', 'True', 'INTERMEDIATE')>: {'link': '/story/step/3', 'name': u'View Results'},
<Category('Analyze', 'True', 'False', 'False', 'FINAL')>: {'link': '/story/step/2', 'name': u'Analyze'}}
Category is a class representing an instance from a database. Now I have the following instance:
<Category('Analyze', 'True', 'False', 'False', 'FINAL')>
Now this is not the same instance. By this I mean, I get all the values from the database and create the dictionary. Then after a while I get an id and retrieve the instance from the database. Now they are not the same objects. I now have to check if it's in the dictionary, but:
instance in disctionary
Will return false. Now I could go the ugly way and iterate over the dictionary checking if all the values match, however does Python have a more clever way to do this? I mean something like the equivalent of Comparable in Java?
Comparable , represents an object which can be compared to other objects. For instance, numbers can be compared, strings can be compared using alphabetical comparison etc. Several of the built-in classes in Java implements the Java Comparable interface.
Comparable v/s Comparator in JavaComparable interface is used to sort the objects with natural ordering. Comparator in Java is used to sort attributes of different objects. Comparable interface compares “this” reference with the object specified. Comparator in Java compares two different class objects provided.
Java Comparable interface is used to order the objects of the user-defined class. This interface is found in java. lang package and contains only one method named compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the elements on the basis of single data member only.
To make classes comparable, you only need to implement __lt__ and decorate the class with functools. total_ordering . You should also provide an __eq__ method if possible. This provides the rest of the comparison operators so you don't have to write any of them yourself.
First: use True
and False
(boolean properties) instead of 'True'
and 'False'
(string properties).
Generally, you can make everything comparable in Python. You just have to define specific methods (like __eq__
, __lt__
, etc.) for your class.
So, let's say I want to compare instances of class A, and the comparison should be just case-insensitive string comparison of s
member:
class A(object):
def __init__(self, s=''):
self.s = s
def __eq__(self, other):
return self.s.lower() == other.s.lower()
a = A('aaaa')
b = A('AAAA')
print a == b # prints True
b = A('bbbb')
print a == b # prints False
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With