我的 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 theinspect
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/