Are classobjects singletons?

后端 未结 2 887
挽巷
挽巷 2020-12-06 11:17

If we have x = type(a) and x == y, does it necessarily imply that x is y?

Here is a counter-example, but it\'s a cheat:

<
2条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-12-06 11:34

    I'm not aware of any documentation about how == works for types, but it definitely works by identity. You can see that the CPython 2.7 implementation is a pointer comparison:

    static PyObject*
    type_richcompare(PyObject *v, PyObject *w, int op)
    {
        ...
    
        /* Compare addresses */
        vv = (Py_uintptr_t)v;
        ww = (Py_uintptr_t)w;
        switch (op) {
        ...
        case Py_EQ: c = vv == ww; break;
    

    In CPython 3.5, type doesn't implement its own tp_richcompare, so it inherits the default equality comparison from object, which is a pointer comparison:

    PyTypeObject PyType_Type = {
        ...
        0,                                          /* tp_richcompare */
    

提交回复
热议问题