File tree Expand file tree Collapse file tree 2 files changed +54
-3
lines changed Expand file tree Collapse file tree 2 files changed +54
-3
lines changed Original file line number Diff line number Diff line change @@ -24,8 +24,8 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
24
24
1 . ` dict_incorrect.py ` : code that counts the words in a text read from standard
25
25
input. The counts are subsequently normalized to ` float ` , which is a type
26
26
error.
27
- 1 . ` dict_correct_type_statement.py ` : same code as ` dict_correct.py ` , but
28
- with a type variable as type statement.
27
+ 1 . ` dict_correct_type_statement.py ` : same code as ` dict_correct.py ` , but with a
28
+ type variable as type statement.
29
29
1 . ` people_incorrect.py ` : code that defines a ` People ` class, stores some in a
30
30
list with mistakes.
31
31
1 . ` duck_typing.py ` : example code illustrating duck typing.
@@ -42,4 +42,7 @@ Type checking can be done using [mypy](http://mypy-lang.org/index.html).
42
42
1 . ` classes.py ` : illustration of using type hints with a user-defined class.
43
43
1 . ` classes_incorrect.py ` : illustration of using type hints with a user-defined
44
44
class with errors.
45
- 1 . ` tree.py ` : illustration of using type hints on more sophisticated classes, as well as generic types.
45
+ 1 . ` tree.py ` : illustration of using type hints on more sophisticated classes,
46
+ as well as generic types.
47
+ 1 . ` new_types.py ` : illustration of using ` NewType ` to create specific types
48
+ with specific semantics.
Original file line number Diff line number Diff line change
1
+ #!/usr/bin/env python
2
+
3
+ from typing import NewType
4
+
5
+ PersonId = NewType ('PersonId' , int )
6
+ Age = NewType ('Age' , int )
7
+
8
+ class Person :
9
+ _person_id : PersonId
10
+ _age : Age
11
+
12
+ def __init__ (self , person_id : PersonId , age : Age ) -> None :
13
+ self ._person_id = person_id
14
+ self ._age = age
15
+
16
+ @property
17
+ def person_id (self ) -> PersonId :
18
+ return self ._person_id
19
+
20
+ @person_id .setter
21
+ def person_id (self , person_id : PersonId ) -> None :
22
+ self ._person_id = person_id
23
+
24
+ @property
25
+ def age (self ) -> Age :
26
+ return self ._age
27
+
28
+ @age .setter
29
+ def age (self , age : Age ) -> None :
30
+ self ._age = age
31
+
32
+ def __repr__ (self ) -> str :
33
+ return f'Person(person_id={ self .person_id } , age={ self .age } )'
34
+
35
+
36
+ if __name__ == '__main__' :
37
+ person = Person (PersonId (1 ), Age (20 ))
38
+ print (person )
39
+ person .person_id = PersonId (2 )
40
+ person .age = Age (30 )
41
+ print (person )
42
+ print (person .person_id )
43
+ print (person .age )
44
+ print (person .person_id + 1 )
45
+ print (person .age + 1 )
46
+ print (person .person_id + person .age )
47
+ person .age = PersonId (40 )
48
+ person .age = 25
You can’t perform that action at this time.
0 commit comments