跟运算符无关的特殊方法
字符串 / 字节序列表示形式: __str__
,__repr__
,__format__
,__bytes__
数值转换: __abs__
、__bool__
、__complex__
、__int__
、__float__
、__hash__
、__index__
集合模拟: __len__、__getitem__、__setitem__、__delitem__、__contains__
迭代枚举: __iter__、__reversed__、__next__
可调用模拟:__call__
上下文管理器: __enter__、__exit__
实例创建和销毁: __new__、__init__、__del__
属性管理: __getattr__、__getattribute__、__setattr__、__delattr__、__dir__
属性描述符: __get__、__set__、__delete__
跟类相关的服务:__prepare__、__instancecheck__、__subclasscheck__
跟运算符相关的特殊方法
一元运算符: __neg__ -、__pos__ +、__abs__ abs()
众多比较运算符: __lt__ 、__ge__ >=
算术运算符: __add__ +、__sub__ -、__mul__ *、__truediv__ /、__floordiv__ //、__mod__ %、__divmod__ divmod()、__pow__ ** 或pow()、__round__ round()
反向算术运算符: __radd__、__rsub__、__rmul__、__rtruediv__、__rfloordiv__、__rmod__、__rdivmod__、__rpow__
增量赋值算术运算符: __iadd__、__isub__、__imul__、__itruediv__、__ifloordiv__、__imod__、__ipow__
位运算符: __invert__ ~、__lshift__ <>、__and__ &、__or__ |、__xor__ ^
反向位运算符:__rlshift__、__rrshift__、__rand__、__rxor__、__ror__
增量赋值位运算符: __ilshift__、__irshift__、__iand__、__ixor__、__ior__
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
|
名称
说明
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
--
-
__init__
(
self
,
.
.
.
)
这个方法在新建对象恰好要被返回使用之前被调用。
__del__
(
self
)
恰好在对象要被删除之前调用。
__str__
(
self
)
在我们对对象使用
print语句或是使用
str
(
)的时候调用。
__lt__
(
self
,
other
)
当使用
小于
运算符(
<)的时候调用。类似地,对于所有的运算符(
+,
>等等)都有特殊的方法。
__getitem__
(
self
,
key
)
使用
x
[
key
]索引操作符的时候调用。
__len__
(
self
)
对序列对象使用内建的
len
(
)函数的时候调用。
__repr__
(
s
)
repr
(
)
and
`
.
.
.
`
conversions
__cmp__
(
s
,
o
)
Compares
s
to
o
and
returns
<
0
,
0
,
or
>
0.
Implements
>
,
<
,
==
etc
.
.
.
__hash__
(
s
)
Compute
a
32
bit
hash
code
;
hash
(
)
and
dictionary
ops
__nonzero__
(
s
)
Returns
0
or
1
for
truth
value
testing
__getattr__
(
s
,
name
)
called
when
attr
lookup
doesn
't find
__setattr__(s, name, val) called when setting an attr
(inside, don'
t
use
"self.name = value"
use
"self.__dict__[name] = val"
)
__delattr__
(
s
,
name
)
called
to
delete
attr
<
name
>
__call__
(
self
,
*
args
)
called
when
an
instance
is
called
as
function
.
|