小编Pra*_*wal的帖子

所有 Python dunder 方法的列表 - 您需要实现哪些方法才能正确代理对象?

我正在尝试创建一个对象代理。属性/属性查找可以通过简单地实现__getattribute__,__setattr____delattr__方法来完成。但是,其他功能如len(x), x[], bool(x)需要其他 dunder 方法__len__, __getitem__, __bool__来实现。如果您没有在代理类上实现这些,但是您代理的对象支持它们,您的代理将不完整并导致运行时错误。

因此,我想拥有一份我需要实施的所有事情的综合清单,但我在网上找不到任何可靠的清单。

这是我从typingbuiltins模块中获得的 97 个独特的 dunder 方法名称。我知道他们中的很多人在做什么,但有些人我不知道。为我的代理类实现所有或大部分它们会很痛苦,所以如果有解决方法我会很高兴。

__abs__
__add__
__aenter__
__aexit__
__aiter__
__and__
__anext__
__await__
__bool__
__bytes__
__call__
__class__
__cmp__
__complex__
__contains__
__delattr__
__delete__
__delitem__
__delslice__
__dir__
__div__
__divmod__
__enter__
__eq__
__exit__
__float__
__floordiv__
__format__
__fspath__
__ge__
__get__
__getattribute__
__getitem__
__getnewargs__
__getslice__
__gt__
__hash__
__iadd__
__iand__
__import__
__imul__
__index__
__init__
__init_subclass__
__instancecheck__
__int__
__invert__
__ior__
__isub__
__iter__
__ixor__
__le__
__len__ …
Run Code Online (Sandbox Code Playgroud)

python-datamodel magic-methods python-3.x proxy-object

14
推荐指数
1
解决办法
4860
查看次数

MyPy 不允许受约束的 TypeVar 是协变的?定义具有约束但协变的键值类型的通用字典

我正在尝试定义一个自定义的通用 dict,它的键是 type T_key,值是 type T_val
我还想对T_keyand施加约束T_val,这样T_key只能是类型AorB或它们的子类。

我该如何实现?

from typing import TypeVar, Generic

class A: ...
class B: ...

class Asub(A): ...
class Bsub(B): ...

T_key = TypeVar('T_key', A, B, covariant=True)
T_val = TypeVar('T_val', A, B, covariant=True)


class MyDict(Generic[T_key, T_val]): ...


w: MyDict[   A,    B]
x: MyDict[   A, Bsub]
y: MyDict[Asub,    B]
z: MyDict[Asub, Bsub]
Run Code Online (Sandbox Code Playgroud)

当我尝试检查这一点时,mypy 在x,y和 的注释上给出了错误z。只有注释w按预期工作。

generic.py:17: error: …
Run Code Online (Sandbox Code Playgroud)

generics covariance python-3.x mypy

2
推荐指数
1
解决办法
1363
查看次数