I’m a little confused by the following example from the python documentation here.
>>> class inch(float):
... "Convert from inch to meter"
... def __new__(cls, arg=0.0):
... return float.__new__(cls, arg*0.0254)
...
>>> print inch(12)
0.3048
>>>
Presumably, float is here is the actual float class defined somewhere deep inside Python. When we call float.__new__(cls, argument) , we’re sneakily calling the function that returns instances of float for a given argument, but we’re passing it the inch class instead of the float class. Since the inch class doesn’t really do anything, why does this work?
Because
inchis a subclass of float, it satisfies all the requirements that thefloat.__new__()instance factory has. It is the job of the__new__(cls)static method to create instances of the first argument, not of it’s ‘own’ class.Note the word ‘static method’ there. The
__new__factory is really just a specialist function tied to a class only for inheritance reasons. In other words, it is a function that plays well in a object-oriented hierarchy. You are supposed to find it viasuper()or perhaps call it directly (as done here). The following would actually be a little more pythonic:because that would call the ‘correct’
__new__function ifinchwere to be used in a multiple-inheritance hierarchy; in this simple example it’ll end up callingfloat.__new__just the same.So,
__new__(cls, ...)is expected to create an instance of typecls. Why then tie it to a class at all and not make it a more generic function then? Because in the case offloat.__new__(cls, value)it not only creates a new instance of typecls, it also sets it’s initial value tovalue. And in order for that to work,float.__new__(...)needs to have intimate knowledge of what thefloatclass looks like. Becauseinch()is a subclass offloat(), it has the exact same necessary bits to be afloat()too, and thus when thefloat.__new__()factory creates a newinchinstance, all those bits are there to make it ainch()instance instead.