-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path03_decorators.py
More file actions
90 lines (48 loc) · 1.44 KB
/
03_decorators.py
File metadata and controls
90 lines (48 loc) · 1.44 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
90
# Decorator
def no_negative(func):
def wrapped(number):
if number < 0:
print("No negative number please.")
else:
func(number)
return wrapped
@no_negative
def add_apple(number):
#number = kwargs.get("number")
print ("Added {} Apples in the basket.".format(number))
# print 'add_apple(5, "apple")'
# #add_apple(5, "apple")
# print 'add_apple(number=5, name="apple")'
# add_apple(number=5, name="apple")
# print 'add_apple(name="apple", number=5)'
# add_apple(name="apple", number=5)
# print 'add_apple(5, color="green", name="apple")'
# #add_apple(5, color="green", name="apple")
# add_apple(5)
# add_apple(-5)
# exit(0)
# Decorator Adv
def no_negative_generic(func):
def wrapped(*args, **kwargs):
count = kwargs.get('count', None)
stuff = kwargs.get('name', None)
if count is None:
print "How many to add?"
return None
if not isinstance(count, int):
print "Give me some int please.."
return None
if stuff is None:
print "What is it?"
return None
if count < 0:
print("No negative count please.")
else:
func(*args, **kwargs)
return wrapped
@no_negative_generic
def add(name=None, count=None):
print ("Added {} {}s in the basket.".format(count, name))
add(name="Apple", count=5)
add(count=5)
add(name="Orange", count=10)