0

クラスの外から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

私はそれをすることができないようです。

4

2 に答える 2

4

これを実際に把握する唯一の方法は、スーパークラス がそれをどう処理するかを調べるShapeことです。それ自体が属性として格納されている場合は、それを取得できます。

于 2013-11-03T20:46:27.153 に答える
1

あなたの状況での汚いハッキーな(あなたが知っている)方法の1つは、ラップ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)>]
于 2013-11-03T20:48:15.097 に答える