|
6 | 6 |
|
7 | 7 | ### 今日更新
|
8 | 8 |
|
9 |
| -**【2019年12月19日】** 计算任意维坐标中两点之间距离 |
| 9 | +**【2019年12月20日】** 让实例也能被调用 |
10 | 10 |
|
| 11 | +Python自定义一个类Student,如下: |
11 | 12 | ```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 | + |
16 | 20 | ```
|
| 21 | +创建实例:`xiaoming`: |
17 | 22 |
|
18 | 23 | ```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 | + |
21 | 41 | ```
|
| 42 | +再次调用: |
| 43 | +```python |
| 44 | +In[1]: xiaoming = Student('001','xiaoming') |
22 | 45 |
|
| 46 | +In[2]: xiaoming() |
| 47 | +OUT[2]: Now, I can be called |
| 48 | +my name is xiaoming |
| 49 | +``` |
23 | 50 |
|
24 | 51 |
|
25 | 52 | ### 一、Python之基
|
|
0 commit comments