iter()

用来生成迭代器,搭配 next() 使用

1
2
3
4
5
6
7
8
9
10
11
12
13
14
def dtime_iterator():
dtime_lst = [1, 2, 3]
return iter(dtime_lst)

it = dtime_iterator()

In [2]: next(it)
Out[2]: 1

In [3]: next(it)
Out[3]: 2

In [4]: next(it)
Out[4]: 3

__call__

调用 function abc(x1, x2 ...) 其实就相当于 type(abc).\__call__(abc, x1, x2 ...)

1
2
3
4
5
6
class Person:
def __call__(self, other):
return f'Hi {other}'

In [13]: Person()("cxs")
Out[13]: 'Hi cxs'

_str_ 和 _repr_

1
2
3
4
5
6
7
8
9
10
11
12
13
14
class CXS:
def __str__(self):
# 实现对象的printshu
return "cxs_str"

def __repr__(self):
return "cxs_repr"

In [6]: print(CXS())
cxs_str

In [8]: cxs = CXS()
In [9]: cxs
Out[9]: cxs_repr

_getitem_

实现对象的 obj[key] 方式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
class DataBase:

def __init__(self, id, address):
self.id = id
self.address = address

def __getitem__(self, key):
return self.__dict__.get(key, "100")

In [13]: db = DataBase(1, "192.168.2.11")
In [14]: db.__dict__
Out[14]: {'id': 1, 'address': '192.168.2.11'}
In [16]: db["id"]
Out[16]: 1
In [17]: db["cxs"]
Out[17]: '100'

_file_

获取当前文件的完整路径

1
2
3
4
5
In [75]: !type cxs.py
print(__file__)

In [76]: %run cxs.py
C:\Users\chen_xiaosheng\Desktop\cxs.py