I\'m a little confused by the following example from the python documentation here.
>>> class inch(float):
... \"Convert from inch to meter\"
...
A little background is needed to answer this question:
object.__new__()
can create a new instances
type of objects, this
kind of objects cannot be subclassed.type
, which can be assigned when passing the type name
cls
to __new__(cls)
as the first argument. class
keyword creats
another kind of objects: classes (a.k.a types), and these kinds of objects
can be subclassed.Now, go back to your example, what
float.__new__(cls, argument)
essentially does is using object.__new__(cls)
to create a new instance (float.__base__
is object
),
assign the type cls
(inch
in this case) to it, and also does something with argument
defined in float.__new__
.
So it is not surprising that it'd work when cls
isn't float
but inch
: the class/type is already created by class inch(float)
, you are just assigning this type to a new instance.