What is wrong this wrapper (decorator)?
fl
rxjwg98 at gmail.com
Sat Nov 14 12:23:33 EST 2015
Hi,
I follow a tutorial to learn decorator:
http://simeonfranklin.com/blog/2012/jul/1/python-decorators-in-12-steps/
I use Enthought Canopy to run the following code.
It is really strange that the wrapper does not take effect.
In fact, I go back to the basic way (not with @):
wrapper(sub(two, one))
Out[38]: <function checker>
When I use the non-wrapper mode, it has Coord print out.
If I use wrapper, it has nothing to print out.
Due to no debug mode help, I don't see anything wrong yet.
(add(two, one))
# nothing print out
(sub(two, three))
Out[43]: Coord:-- {'y': 300, 'x': 400} # correct is here
Anyone can help?
Thanks,
............
class Coordinate(object):
def __init__(self, y, x):
self.y = y
self.x = x
def __repr__(self):
return "Coord:-- " + str(self.__dict__)
def add(a, b):
return Coordinate(a.x + b.x, a.y + b.y)
def sub(a, b):
return Coordinate(a.x - b.x, a.y - b.y)
def wrapper(func):
def checker(a, b): # 1
if a.x < 0 or a.y < 0:
a = Coordinate(a.x if a.x > 0 else 0, a.y if a.y > 0 else 0)
if b.x < 0 or b.y < 0:
b = Coordinate(b.x if b.x > 0 else 0, b.y if b.y > 0 else 0)
ret = func(a, b)
if ret.x < 0 or ret.y < 0:
ret = Coordinate(ret.x if ret.x > 0 else 0, ret.y if ret.y > 0 else 0)
return ret
return checker
one = Coordinate(100, 200)
two = Coordinate(300, 200)
three = Coordinate(-100, -100)
add = wrapper(add)
#sub = wrapper(sub)
More information about the Python-list
mailing list