我想知道有没有办法从课外访问coords变量。假设,我无法将coords改为self.coords。
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.center_block = self.blocks[0]
self.shift_rotation_dir = True
self.rotation_dir = -1
我似乎无法做到。
答案 0 :(得分:4)
真正掌握这一点的唯一方法是查看超类Shape
对它的作用。如果它将它作为一个属性存储,你就可以掌握它。
答案 1 :(得分:1)
在你的情况下,一种肮脏的hacky(你知道)方式是wrap Shape.__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)>]