gpt4 book ai didi

python - 一个类的独特方法叫什么?

转载 作者:太空狗 更新时间:2023-10-30 02:15:54 25 4
gpt4 key购买 nike

假设你有一个类,你将它定义为:

class A:
pass

当你使用这个函数时:

dir(A)

返回类包含的所有方法和属性:

['__class__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__']

我的问题是,什么是前后带有双下划线的方法,例如 __class____delattr____dict__ __init__,叫什么?我假设它们被称为构造函数,但经过研究 - 似乎该术语仅指 __init__ 函数。有谁知道是否有一个特定的类别来调用这些方法?

最佳答案

它们被称为 special method names :

Special method names

A class can implement certain operations that are invoked by special syntax (such as arithmetic operations or subscripting and slicing) by defining methods with special names. This is Python’s approach to operator overloading, allowing classes to define their own behavior with respect to language operators.

special attributes :

Some of the type descriptions below contain a paragraph listing ‘special attributes.’ These are attributes that provide access to the implementation and are not intended for general use.

以双下划线开头并以双下划线结尾的名称是保留名称。查看Reserved classes of identifiers :

__*__
System-defined names. These names are defined by the interpreter and its implementation (including the standard library). Current system names are discussed in the Special method names section and elsewhere. More will likely be defined in future versions of Python. Any use of __*__ names, in any context, that does not follow explicitly documented use, is subject to breakage without warning.

它们有时被称为双下划线名称,是双下划线的缩写。 神奇的名字也是对它们的流行称呼,但都不是官方的。

请注意,__init__ 方法是实例初始化器 Hook ,它不是构造函数。调用此方法时已经构造了实例。如果你需要 Hook 到构造中,实现 __new__ method .

关于python - 一个类的独特方法叫什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47496704/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com