Reputation: 309
So, I am reading some code online and I came across the following class definition and I'm a little confused;
class MyClass(OrderedDict):
def __hash__(self):
return hash(tuple(self.iteritems()))
Elsewhere in the code there is the following line;
MyClass(my_OD)
Where my_OD
is an ordered dictionary. My question is, how can you pass an argument to this class when there is no __init__
method? Where is this variable being assigned within the class? I'm coming from Java and I'm fairly certain that in Java you cannot pass an argument to a class without a constructor so this behavior is foreign to me.
Upvotes: 3
Views: 69
Reputation: 15987
The class MyClass
inherits from OrderedDict
:
class MyClass(OrderedDict):
Since MyClass
doesn't have an __init__
method specified, it calls the init method of the OrderedDict class. So the my_OD
argument to the constructor gets passed on to the OrderedDict. Btw, __init__
is not technically the constructor.
The purpose of this MyClass
is to be an OrderedDict which computes the hash
of its instances in a different way than OrderedDict does. Specifically, OrderedDict
doesn't have a __hash__
, that's defined on dict
s and in that case, the hash is defined as None
- so dicts are un-hashable. MyClass
changes that adds a way to get the hash, while the rest of the functionality is the same OrderedDict
s and dict
s.
Upvotes: 6