Python-dir(列表)----函数是什么?

Python-dir(列表)----函数是什么?,python,Python,需要知道它是如何在python脚本中使用的吗?我们是否必须编写一个类并将其用作方法,或者如何编写?有人能用简单的例子解释一下吗?这些是python的“协议”或“dunder(双下划线)方法”或“魔术方法”。用于特殊的python操作,例如\uuuuu add\uuuuuuuuuuuuuuuuuuuuuuoself,other)定义调用self+other时发生的事情,以及\uuuuuuuuuuuuuoself)定义调用str(self)时发生的事情 例如: >>> dir

需要知道它是如何在python脚本中使用的吗?我们是否必须编写一个类并将其用作方法,或者如何编写?有人能用简单的例子解释一下吗?

这些是python的“协议”或“dunder(双下划线)方法”或“魔术方法”。用于特殊的python操作,例如
\uuuuu add\uuuuuuuuuuuuuuuuuuuuuuoself,other)
定义调用
self+other
时发生的事情,以及
\uuuuuuuuuuuuuoself)
定义调用
str(self)
时发生的事情


例如:

>>> dir(list) 

['__add__', '__class__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']

@Chris_Rands我在回答这个问题:“
dir(list)——\uu函数\uuuu
它们是什么?”
In [19]: class Adder:
    ...:     def __init__(self, x):
    ...:         print('in __init__')
    ...:         self.x = x
    ...: 
    ...:     def __add__(self, other):
    ...:         print('in __add__')
    ...:         return self.x + other
    ...: 
    ...:     def __str__(self):
    ...:         print('in __str__')
    ...:         return 'Adder({})'.format(self.x)
    ...: 
    ...:     def __call__(self, value):
    ...:         print('in __call__')
    ...:         return self + value
    ...:     

In [20]: a = Adder(3)
in __init__

In [21]: a.x
Out[21]: 3

In [22]: a + 12
in __add__
Out[22]: 15

In [23]: str(a)
in __str__
Out[23]: 'Adder(3)'

In [24]: a(3)
in __call__
in __add__
Out[24]: 6