在您的情况下,一种肮脏的 hacky(您知道)方法是 wrapShape.__init__
方法并在以下范围内工作:
class Coords():
def __init__(self, x, y):
self.x = x
self.y = y
class Point(Coords):
def __repr__(self):
return '<Point ({} {})>'.format(self.x, self.y)
class Shape():
def __init__(self, *args, **kw):
pass
class S_shape(Shape):
def __init__(self, center):
coords = [Point(center.x, center.y),
Point(center.x, center.y + 1),
Point(center.x + 1, center.y),
Point(center.x - 1, center.y + 1)]
Shape.__init__(self, coords, 'green')
self.shift_rotation_dir = True
self.rotation_dir = -1
def coordinates_logger(func):
def wrapper(self, coords, color): # assume we need exactly first arg to __init__
print coords # access to coords, perform some needed action here
self._coords = coords # for example store them
return func(self, coords, color)
wrapper.__name__ = func.__name__
wrapper.__doc__ = func.__doc__
wrapper.__dict__.update(func.__dict__)
return wrapper
# monkey-patch superclass
Shape.__init__ = coordinates_logger(Shape.__init__)
obj = S_shape(Coords(1,2))
# [<Point (1 2)>, <Point (1 3)>, <Point (2 2)>, <Point (0 3)>]
print obj._coords
# [<Point (1 2)>, <Point (1 3)>, <Point (2 2)>, <Point (0 3)>]