如何在Pythonclass中正确"stub"__objclass__?

How to correctly "stub" __objclass__ in a Python class?

我 Python class 看起来有点像这样:

class some_class:
    def __getattr__(self, name):
        # Do something with "name" (by passing it to a server)

有时,我会使用 ptpython(交互式 Python shell)进行调试。 ptpython 检查 class 的实例并尝试访问不存在的 __objclass__ 属性。在 __getattr__ 中,我可以在使用 name 之前简单地检查 if name != "__objclass__",但我想知道是否有更好的方法通过正确实施或以某种方式存根 __objclass__ .

Python documentation 并没有说太多,或者至少我不明白我必须做什么:

The attribute __objclass__ is interpreted by the inspect module as specifying the class where this object was defined (setting this appropriately can assist in runtime introspection of dynamic class attributes). For callables, it may indicate that an instance of the given type (or a subclass) is expected or required as the first positional argument (for example, CPython sets this attribute for unbound methods that are implemented in C).

您想避免干扰此属性。没有理由手动进行任何类型的存根操作——您想避开并让它做它通常做的事情。如果它的行为像属性通常那样,一切都会正常工作。

因此,正确的实现是 special-case __getattr__ 函数中的 __objclass__ 属性并抛出一个 AttributeError.

class some_class:
    def __getattr__(self, name):
        if name == "__objclass__":
            raise AttributeError

        # Do something with "name" (by passing it to a server)

这种方式的行为方式与在没有 __getattr__ 的 class 中的行为方式相同:默认情况下,该属性被视为 non-existant,直到它被分配给。如果属性已经存在,则不会调用 __getattr__ 方法,因此可以毫无问题地使用它:

>>> obj = some_class()
>>> hasattr(obj, '__objclass__')
False
>>> obj.__objclass__ = some_class
>>> obj.__objclass__
<class '__main__.some_class'>