Моя проблема заключается в создании единого, сплоченного алгоритма в C ++, который правильно обрабатывает все сценарии поиска, которые кажутся конфликтыми в первом сроке.
< /p>
Я пытаюсь согласовать логику для следующих случаев: < /p>
Код: Выделить всё
# Case 1: Method on an instance
# The lookup should find `__str__` on the `int` type and "bind" it
# to the instance `3` to provide `self`.
(3).__str__()
# Case 2: Method on a type (Metaclass)
# Here, the lookup should happen on the type of `int` (the metaclass, `type`),
# find the `__str__` defined there, and bind it to the `int` type object.
# The expected result is the string "", not the same function from Case 1.
int.__str__()
# Case 3: Attribute on an instance
# The lookup seems to start directly at the `3` object to return its type.
(3).__class__ # Returns the `int` type object
# Case 4: Attribute on a type
# The lookup starts at the `int` object to return its type.
int.__class__ # Returns the `type` metaclass object
В моей реализации C ++ у меня есть базовые классы pyobject и pytypeobject . Моя первая попытка состояла в том, чтобы создать две отдельные функции Find , одна для экземпляров и другая для типов, но это чувствует себя неправильно и не решает проблему единым способом.
Код: Выделить всё
// Pseudo-code of my flawed attempt
struct PyObject {
PyTypeObject* ob_type;
Scope* scope; // My __dict__
// Lookup on instances
virtual PyObject* find(string name) {
// 1. Check my instance's __dict__ (scope)
// 2. If not found, search the MRO of my type
// ...
}
};
struct PyTypeObject : PyObject {
// Lookup on types (override)
PyObject* find(string name) override {
// Different logic that searches the metaclass MRO
// ...
}
};
< /code>
Этот подход не кажется правильным. Мое исследование показывает, что ключом к объединению этого является протокол дескриптора (в частности __get __
и обработка данных и не дате-десптор? Unified Algorithm для
dinfive между вызовом на экземпляре (например (3) .__ str __ < /code>) и
вызов на тип (например, int .__ str __ < /code>)? В качестве ссылки для моей реализации C ++ было бы
невероятно полезно. < /p>
< /li>
< /ol>
Любое объяснение, псевдокод или указатели на то, как CPYTHON реализует его TP_GetAttro < /code> слот был бы очень полезным. Спасибо!
Подробнее здесь: https://stackoverflow.com/questions/796 ... te-in-c-ha