Python: Why would float.__new__(cls) work when cls isn't float?

后端 未结 2 1149
暗喜
暗喜 2021-01-25 07:26

I\'m a little confused by the following example from the python documentation here.

>>> class inch(float):
...     \"Convert from inch to meter\"
...            


        
2条回答
  •  广开言路
    2021-01-25 08:00

    A little background is needed to answer this question:

    1. Only object.__new__() can create a new instances type of objects, this kind of objects cannot be subclassed.
    2. An instance has a 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.

提交回复
热议问题