Skip to content

Commit 02d1f46

Browse files
author
guozhen3
committed
call()
1 parent efabed5 commit 02d1f46

File tree

1 file changed

+34
-7
lines changed

1 file changed

+34
-7
lines changed

README.md

Lines changed: 34 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -6,20 +6,47 @@
66

77
### 今日更新
88

9-
**2019年12月19日** 计算任意维坐标中两点之间距离
9+
**2019年12月20日** 让实例也能被调用
1010

11+
Python自定义一个类Student,如下:
1112
```python
12-
import math
13-
def distance(p0,p1,digits=2):
14-
a=map(lambda p: (p[0]-p[1])**2, zip(p0, p1))
15-
return round(math.sqrt(sum(a)),digits)
13+
class Student():
14+
...: def __init__(self,id,name):
15+
...: self.id = id
16+
...: self.name = name
17+
...: def __repr__(self):
18+
...: return 'id = '+self.id +', name = '+self.name
19+
1620
```
21+
创建实例:`xiaoming`:
1722

1823
```python
19-
distance((1,1),(2,2),digits=5) # 1.41421
20-
distance((1,2,3,4),(4,3,2,1)) # 4.47
24+
xiaoming = Student('001','xiaoming')
25+
xiaoming() # TypeError: 'Student' object is not callable
26+
```
27+
此时调用实例`xiaomng()`会抛出TypeError实例不能被调用的异常。
28+
29+
重写`__call__ `方法,实现`xiaomng()`可被调用:
30+
```python
31+
class Student():
32+
...: def __init__(self,id,name):
33+
...: self.id = id
34+
...: self.name = name
35+
...: def __repr__(self):
36+
...: return 'id = '+self.id +', name = '+self.name
37+
...: def __call__(self):
38+
...: print('Now, I can be called')
39+
...: print(f'my name is {self.name}')
40+
2141
```
42+
再次调用:
43+
```python
44+
In[1]: xiaoming = Student('001','xiaoming')
2245

46+
In[2]: xiaoming()
47+
OUT[2]: Now, I can be called
48+
my name is xiaoming
49+
```
2350

2451

2552
### 一、Python之基

0 commit comments

Comments
 (0)