-
Notifications
You must be signed in to change notification settings - Fork 1
/
duck_typing.py
77 lines (52 loc) · 1.32 KB
/
duck_typing.py
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
class Duck:
def quack(self):
print('Quack, quack')
def fly(self):
print('Flap, Flap!')
class Person:
def quack(self):
print("I'm Quacking like a Duck!")
def fly(self):
print("I'm Flapping my Arms!")
# def quack_and_fly(thing):
# # Not Duck-Typed(Non-Pythonic)
# if isinstance(thing, Duck):
# thing.quack()
# thing.fly()
# else:
# print("This has to be a Duck!")
# print()
def quack_and_fly(thing):
# EAFP (pythonic)
try:
thing.quack()
thing.fly()
except AttributeError as e:
print(e)
print()
d = Duck()
quack_and_fly(d)
p = Person()
quack_and_fly(p)
person = {'name': 'John', 'age': 25, 'job': 'Programmer'}
# LBYL (Non-pythonic)
if 'name' in person and 'age' in person and 'job' in person:
print("I'm {name}. I'm {age} years old and an a {job}".format(**person))
else:
print("Missing some keys")
# EAFP (pythonic)
try:
print("I'm {name}. I'm {age} years old and an a {job}".format(**person))
except KeyError as e:
print("Missing {} key".format(e))
my_list = [1, 2, 3, 4, 5, 6]
# non pythonic
if len(my_list) >= 6:
print(my_list[5])
else:
print("That index does not exist")
# pythonic
try:
print(my_list[5])
except IndexError:
print("That index does not exist")