python - 如何在Python类中正确显示 "stub"__objclass__?

标签 python python-3.x class inspect ptpython

我的 Python 类看起来有点像这样:

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

有时,我正在与 ptpython 一起工作(交互式 Python shell)用于调试。 ptpython检查类的实例并尝试访问 __objclass__属性,该属性不存在。在 __getattr__ ,我可以简单地检查 if name != "__objclass__"在使用 name 之前,但我想知道是否有更好的方法,通过正确实现或以某种方式 stub __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).

最佳答案

您希望避免干扰此属性。没有理由手动进行任何类型的 stub - 您想要摆脱困境并让它做它通常做的事情。如果它的行为像属性通常那样,那么一切都会正常工作。

因此,正确的实现是将 __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__ 的类中的行为方式相同:默认情况下,该属性被视为不存在,直到它被分配为止。如果属性已经存在,则不会调用 __getattr__ 方法,因此可以毫无问题地使用它:

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

关于python - 如何在Python类中正确显示 "stub"__objclass__?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49405914/

相关文章:

python - Z3 可以用来预处理问题吗?

python - 如何使用 python 获取 XML 的所有子节点?

python - Mac OS 上导入 boto3 错误

Python Airflow 自定义传感器 - 实现哪些方法

python - 使用selenium,我怎样才能只找到前N个元素来运行得更快?

python - 在函数调用中使用 end =""时出错

python - python 中 1 + 1 可以等于 3 吗?

php - 使用变量引用对象属性

java - 如何访问类的动态创建对象的方法和属性

python - 将文件转换为字典?