特殊方法的 Python 文档在哪里? (__init__, __new__, __len__, ...)

发布于 2024-08-05 04:47:03 字数 130 浏览 8 评论 0原文

哪里有可以在类中使用的特殊双下划线/dunder 方法的完整列表? (例如,__init____new____len____add__

Where is a complete list of the special double-underscore/dunder methods that can be used in classes? (e.g., __init__, __new__, __len__, __add__)

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(9

德意的啸 2024-08-12 04:47:03

请查看 Python 中的特殊方法名称部分语言参考。

Please take a look at the special method names section in the Python language reference.

最单纯的乌龟 2024-08-12 04:47:03

如果你像我一样想要一份简单、朴素的清单,那就在这里。我根据 Python 文档链接 编译了它接受的答案。

__abs__
__add__
__and__
__call__
__class__
__cmp__
__coerce__
__complex__
__contains__
__del__
__delattr__
__delete__
__delitem__
__delslice__
__dict__
__div__
__divmod__
__eq__
__float__
__floordiv__
__ge__
__get__
__getattr__
__getattribute__
__getitem__
__getslice__
__gt__
__hash__
__hex__
__iadd__
__iand__
__idiv__
__ifloordiv__
__ilshift__
__imod__
__imul__
__index__
__init__
__instancecheck__
__int__
__invert__
__ior__
__ipow__
__irshift__
__isub__
__iter__
__itruediv__
__ixor__
__le__
__len__
__long__
__lshift__
__lt__
__metaclass__
__mod__
__mro__
__mul__
__ne__
__neg__
__new__
__nonzero__
__oct__
__or__
__pos__
__pow__
__radd__
__rand__
__rcmp__
__rdiv__
__rdivmod__
__repr__
__reversed__
__rfloordiv__
__rlshift__
__rmod__
__rmul__
__ror__
__rpow__
__rrshift__
__rshift__
__rsub__
__rtruediv__
__rxor__
__set__
__setattr__
__setitem__
__setslice__
__slots__
__str__
__sub__
__subclasscheck__
__truediv__
__unicode__
__weakref__
__xor__

If, like me, you want a plain, unadorned list, here it is. I compiled it based on the Python documentation link from the accepted answer.

__abs__
__add__
__and__
__call__
__class__
__cmp__
__coerce__
__complex__
__contains__
__del__
__delattr__
__delete__
__delitem__
__delslice__
__dict__
__div__
__divmod__
__eq__
__float__
__floordiv__
__ge__
__get__
__getattr__
__getattribute__
__getitem__
__getslice__
__gt__
__hash__
__hex__
__iadd__
__iand__
__idiv__
__ifloordiv__
__ilshift__
__imod__
__imul__
__index__
__init__
__instancecheck__
__int__
__invert__
__ior__
__ipow__
__irshift__
__isub__
__iter__
__itruediv__
__ixor__
__le__
__len__
__long__
__lshift__
__lt__
__metaclass__
__mod__
__mro__
__mul__
__ne__
__neg__
__new__
__nonzero__
__oct__
__or__
__pos__
__pow__
__radd__
__rand__
__rcmp__
__rdiv__
__rdivmod__
__repr__
__reversed__
__rfloordiv__
__rlshift__
__rmod__
__rmul__
__ror__
__rpow__
__rrshift__
__rshift__
__rsub__
__rtruediv__
__rxor__
__set__
__setattr__
__setitem__
__setslice__
__slots__
__str__
__sub__
__subclasscheck__
__truediv__
__unicode__
__weakref__
__xor__
治碍 2024-08-12 04:47:03

Dive Into Python 有一个优秀的附录

Dive Into Python has an excellent appendix for them.

人疚 2024-08-12 04:47:03

如果您更喜欢从 CLI 而不是浏览器阅读文档,请执行此操作。

$ pydoc特殊方法

Do this if you prefer reading documentation from a CLI instead of the browser.

$ pydoc SPECIALMETHODS

梦里南柯 2024-08-12 04:47:03

对于那些对 Python 相对较新的人来说,文档通常不太容易访问(比如我自己):有人写了 很好的介绍,有很多关于特殊(魔术)方法如何工作、如何使用它们等的示例。

For somebody who is relatively new to Python, and for whom the documentation is often not quite accessible enough (like myself): somebody wrote a nice introduction with lots of examples on how the special (magic) methods work, how to use them, etc.

去了角落 2024-08-12 04:47:03

Python 的双下划线(“dunder”)方法也称为 datamodel 方法,因为它们是 Python 数据模型的核心,提供了用于自定义(重载)内置方法的协议。
这就是为什么它们被列在“数据模型”中的原因Python 文档的 部分。

Python's double underscore ("dunder") methods are also known as datamodel methods because they are at the core of Python's data model, providing a protocol for customizing (overloading) built-in methods.
This is the reason why they are listed in the "Data Model" section of the Python's documentation.

鹤仙姿 2024-08-12 04:47:03

根据@Justin的回答,他包含了95个项目,以下是我可以推断出的dunder方法: # 105 on 2.7 and 108 on 3.10:

from functools import partial
from itertools import chain


# From https://github.com/Suor/funcy/blob/0ee7ae8/funcy/funcs.py#L34-L36
def rpartial(func, *args):
    """Partially applies last arguments."""
    return lambda *a: func(*(a + args))


dunders = tuple(filter(rpartial(str.startswith, "__"),
                frozenset(chain.from_iterable((
# https://docs.python.org/3/library/stdtypes.html
                    chain.from_iterable(map(dir, (int, float, complex,
                                                  list, tuple, range,
                                                  str, bytes,
                                                  # 2.7: unicode,
                                                  bytearray, memoryview,
                                                  set, frozenset, dict, 
                                                  type, None, Ellipsis, 
                                                  NotImplemented, object)
                                            )),
# https://docs.python.org/3/library/functions.html#dir
                    dir(),
# https://docs.python.org/3/library/stdtypes.html#special-attributes
                    ("__dict__", "__class__", "__bases__", "__name__",
                     "__qualname__", "__mro__", "__subclasses__",
# https://docs.python.org/3/reference/datamodel.html#slots
                     "__slots__")
                )))))

Output on 3.10:

('__abs__',
 '__abstractmethods__',
 '__add__',
 '__alloc__',
 '__and__',
 '__annotations__',
 '__base__',
 '__bases__',
 '__basicsize__',
 '__bool__',
 '__builtins__',
 '__cached__',
 '__call__',
 '__ceil__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dict__',
 '__dictoffset__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__enter__',
 '__eq__',
 '__exit__',
 '__file__',
 '__flags__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getformat__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__iand__',
 '__imul__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__instancecheck__',
 '__int__',
 '__invert__',
 '__ior__',
 '__isub__',
 '__itemsize__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__loader__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__module__',
 '__mro__',
 '__mul__',
 '__name__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__package__',
 '__pos__',
 '__pow__',
 '__prepare__',
 '__qualname__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__set_format__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__slots__',
 '__spec__',
 '__str__',
 '__sub__',
 '__subclasscheck__',
 '__subclasses__',
 '__subclasshook__',
 '__text_signature__',
 '__truediv__',
 '__trunc__',
 '__weakrefoffset__',
 '__xor__')

Following on from @Justin's answer, he included 95 items, here are the dunder methods I could infer: # 105 on 2.7 and 108 on 3.10:

from functools import partial
from itertools import chain


# From https://github.com/Suor/funcy/blob/0ee7ae8/funcy/funcs.py#L34-L36
def rpartial(func, *args):
    """Partially applies last arguments."""
    return lambda *a: func(*(a + args))


dunders = tuple(filter(rpartial(str.startswith, "__"),
                frozenset(chain.from_iterable((
# https://docs.python.org/3/library/stdtypes.html
                    chain.from_iterable(map(dir, (int, float, complex,
                                                  list, tuple, range,
                                                  str, bytes,
                                                  # 2.7: unicode,
                                                  bytearray, memoryview,
                                                  set, frozenset, dict, 
                                                  type, None, Ellipsis, 
                                                  NotImplemented, object)
                                            )),
# https://docs.python.org/3/library/functions.html#dir
                    dir(),
# https://docs.python.org/3/library/stdtypes.html#special-attributes
                    ("__dict__", "__class__", "__bases__", "__name__",
                     "__qualname__", "__mro__", "__subclasses__",
# https://docs.python.org/3/reference/datamodel.html#slots
                     "__slots__")
                )))))

Output on 3.10:

('__abs__',
 '__abstractmethods__',
 '__add__',
 '__alloc__',
 '__and__',
 '__annotations__',
 '__base__',
 '__bases__',
 '__basicsize__',
 '__bool__',
 '__builtins__',
 '__cached__',
 '__call__',
 '__ceil__',
 '__class__',
 '__class_getitem__',
 '__contains__',
 '__delattr__',
 '__delitem__',
 '__dict__',
 '__dictoffset__',
 '__dir__',
 '__divmod__',
 '__doc__',
 '__enter__',
 '__eq__',
 '__exit__',
 '__file__',
 '__flags__',
 '__float__',
 '__floor__',
 '__floordiv__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getformat__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__iadd__',
 '__iand__',
 '__imul__',
 '__index__',
 '__init__',
 '__init_subclass__',
 '__instancecheck__',
 '__int__',
 '__invert__',
 '__ior__',
 '__isub__',
 '__itemsize__',
 '__iter__',
 '__ixor__',
 '__le__',
 '__len__',
 '__loader__',
 '__lshift__',
 '__lt__',
 '__mod__',
 '__module__',
 '__mro__',
 '__mul__',
 '__name__',
 '__ne__',
 '__neg__',
 '__new__',
 '__or__',
 '__package__',
 '__pos__',
 '__pow__',
 '__prepare__',
 '__qualname__',
 '__radd__',
 '__rand__',
 '__rdivmod__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__reversed__',
 '__rfloordiv__',
 '__rlshift__',
 '__rmod__',
 '__rmul__',
 '__ror__',
 '__round__',
 '__rpow__',
 '__rrshift__',
 '__rshift__',
 '__rsub__',
 '__rtruediv__',
 '__rxor__',
 '__set_format__',
 '__setattr__',
 '__setitem__',
 '__sizeof__',
 '__slots__',
 '__spec__',
 '__str__',
 '__sub__',
 '__subclasscheck__',
 '__subclasses__',
 '__subclasshook__',
 '__text_signature__',
 '__truediv__',
 '__trunc__',
 '__weakrefoffset__',
 '__xor__')
我是男神闪亮亮 2024-08-12 04:47:03

熟悉 dir 函数。

Familiarize yourself with the dir function.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文