0

我想知道有没有办法从类外访问 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

我似乎无法做到。

4

2 回答 2

4

真正掌握这一点的唯一方法可能是看看超类 ,Shape用它做了什么。如果它自己将其存储为属性,则可以获取它。

于 2013-11-03T20:46:27.153 回答
1

在您的情况下,一种肮脏的 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)>]
于 2013-11-03T20:48:15.097 回答