-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgenericT.py
More file actions
89 lines (58 loc) · 1.79 KB
/
Copy pathgenericT.py
File metadata and controls
89 lines (58 loc) · 1.79 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
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# genericT.py
# -------------------------------
# DEFINING A GENERIC FUNCTION
# -------------------------------
from typing import TypeVar
T = TypeVar('T') # generic type
def show(value: T) -> T:
return value # works with any data type
# -------------------------------
# CALLING GENERIC FUNCTION
# -------------------------------
print(show(10)) # int
print(show(3.14)) # float
print(show("Python")) # string
print(show([1, 2, 3])) # list
# multiple generic types
T1 = TypeVar('T1')
T2 = TypeVar('T2')
def combine(a: T1, b: T2):
return a, b # returns tuple of different types
print(combine(10, "Hi")) # (10, 'Hi')
print(combine(3.5, [1,2])) # (3.5, [1,2])
# -------------------------------
# DEFINING A GENERIC CLASS
# -------------------------------
from typing import Generic
T = TypeVar('T')
class Box(Generic[T]):
def __init__(self, value: T):
self.value = value
def get(self) -> T:
return self.value
def set(self, new_value: T):
self.value = new_value
# -------------------------------
# USING GENERIC CLASS
# -------------------------------
int_box = Box
print(int_box.get()) # 10
str_box = Box[str]("Hello")
print(str_box.get()) # Hello
list_box = Box[list]([1,2,3])
print(list_box.get()) # [1, 2, 3]
# -------------------------------
# GENERIC CLASS WITH MULTIPLE TYPES
# -------------------------------
T1 = TypeVar('T1')
T2 = TypeVar('T2')
class Pair(Generic[T1, T2]):
def __init__(self, first: T1, second: T2):
self.first = first
self.second = second
def get_pair(self):
return self.first, self.second
p1 = Pair[int, str](1, "One")
print(p1.get_pair()) # (1, 'One')
p2 = Pair[str, float]("Value", 2.5)
print(p2.get_pair()) # ('Value', 2.5)