标签:python oop python-3-x naming
如果您有一个类,并将其定义为:
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.
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 07003 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.
它们有时被称为dunder名称,作为双下划线的缩写.魔术名称也是他们的流行术语,但两者都不是官方名称.
请注意,__ init__方法是实例初始化器钩子,它不是构造函数.该方法在调用此方法时已经构建.如果您需要挂钩施工,请执行__new__
method.
标签:python,oop,python-3-x,naming 来源: https://codeday.me/bug/20190611/1216606.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。