-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path2_class_based.py
More file actions
77 lines (50 loc) · 2.16 KB
/
2_class_based.py
File metadata and controls
77 lines (50 loc) · 2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
from typing import TypedDict
class Movie(TypedDict):
name: str
year: int
# Movie is a TypedDict type with two items: 'name' (with type str) and 'year' (with type int).
# Constructor as an ordinary dictionary type
movie: Movie = {"name": "Harry Potter ", "year": 2001}
# TypedDict types are callable at runtime and can be used
# as a constructor to create values that conform to the TypedDict type.
# The constructor takes only keyword arguments,
# corresponding to the items of the TypedDict. Example:
m = Movie(name="Blade Runner", year=1982)
# define a function to accept TypedDict
def func(movie: Movie) -> None:
print(f"printing the type {type(movie)}") # it is type <class 'dict'>
print(f"Movie name {movie['name']}") # obtain the value of the type "name"
print(movie) # {'name': 'Blade Runner', 'year': 1982}
print(type(movie)) # <class, dict>
# call the function with created Movie type object
func(movie)
# call the function with inline argument passing
func({"name": "Blade Runner", "year": 1982})
# define function which return Movie data type
def func2(arg1: str, arg2: int) -> Movie:
return Movie(name=arg1, year=arg2)
myMovie: Movie = func2("Gone with the wind", 1995)
print(myMovie) # {'name': 'Gone with the wind', 'year': 1995}
# Inheritance :
# This creates a TypedDict type BookBasedMovie
# with three items: 'name' (type str), 'year' (type int), and 'based_on' (type str)
class BookBasedMovie(Movie):
based_on: str
def func3(bookstore: BookBasedMovie) -> None:
pass
# More examples . You see how we create a new type called Point2D
class Point2D(TypedDict):
x: int
y: int
label: str
# We inherited from Point2D and added one type called "z"
class Point3D(Point2D):
z: int
a: Point2D = {"x": 1, "y": 2, "label": "good"} # OK
# TypedDict and Dict are the same
assert Point2D(x=1, y=2, label="first") == dict(x=1, y=2, label="first") # ok;
#Type "dict[str, int | str]" is not assignable to declared type "Point3D"
# "x" is required in "Point3D"
# "y" is required in "Point3D"
# "x" and "y" type are mandatory to include by default as per original PEP
b: Point3D = {"z": 3, "label": "bad"} # Fails