-
Notifications
You must be signed in to change notification settings - Fork 0
/
Giang_Wk5_Ex2-2.py
59 lines (46 loc) · 1.46 KB
/
Giang_Wk5_Ex2-2.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
# Alex Giang
# Professor Abolghasemi
# CIS 502
# 25 February 2024
# Week 5-2, Exercise 2
# This file is intended to demonstrate beginning knowledge in implementing
# function wrappers to alter the behavior or return values of functions.
class debug:
def __init__(self, func):
if isinstance(func, type):
self.function = debug.debug_all(func)
else:
self.function = debug.debug_one(func)
def __call__(self, *args, **kwargs):
return self.function(*args, **kwargs)
def debug_all(cls):
for name, value in vars(cls).items():
if callable(value):
setattr(cls, name, debug.debug_one(value))
return cls
def debug_one(func):
def wrapper(*args, **kwargs):
try:
print('Called', func.__name__)
except AttributeError as e:
pass
n = 0
for i in args:
n += 1
print('Attribute', n, 'is', i)
n = 0
for j in kwargs.items():
n += 1
print('Keyword attribute', n, 'is', j)
return func(*args, **kwargs)
return wrapper
@debug
class Calculator:
def add(self, lhs=0, rhs=0):
return lhs + rhs
calc = Calculator()
print(type(Calculator))
print(type(calc))
print(type(calc.add))
print(calc.add(3, 5))
print(calc.add(4 + 2j, rhs=-8j))