Skip to content

Commit 0a11d70

Browse files
committed
Add example for data structure type checking
1 parent 2edd90d commit 0a11d70

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed

source-code/typing/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,3 +38,5 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
3838
matplotlib with type hints.
3939
1. `classes.py`: illustration of using type hints with a user-defined
4040
class.
41+
1. `classes_incorrect.py`: illustration of using type hints with a
42+
user-defined class with errors.
Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,38 @@
1+
#!/usr/bin/env python
2+
3+
from typing import Any
4+
5+
6+
class MyClass:
7+
8+
def __init__(self, data: Any) -> None:
9+
self.data = data
10+
11+
@property
12+
def data(self) -> int:
13+
return self.data
14+
15+
@data.setter
16+
def data(self, value: Any) -> None:
17+
self.data = int(value)
18+
19+
def __repr__(self) -> str:
20+
return f'data: {self.data}'
21+
22+
23+
def print_data(data: MyClass) -> None:
24+
print(data)
25+
26+
27+
def print_all(datas: list[MyClass]) -> None:
28+
for data in datas:
29+
print_data(data)
30+
31+
32+
if __name__ == '__main__':
33+
data = MyClass('25')
34+
print_data(data)
35+
datas = [data]
36+
print_all(datas)
37+
datas.append('354')
38+
print_all(datas)

0 commit comments

Comments
 (0)