>>> 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']
需要知道它在python脚本中的使用方式吗?我们是否必须编写一个类并将它们用作方法或如何?有人可以用简单的例子来解释我吗?
是python的"协议"或"dunder(双下划线(方法"或"魔术方法"。用于特殊的 python 操作,例如__add__(self, other)
定义调用self + other
时会发生什么,__str__(self)
定义调用str(self)
时会发生什么。
https://rszalski.github.io/magicmethods/
https://docs.python.org/3/reference/datamodel.html#special-method-names
例:
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