python PrototypeStore

-- coding: utf-8 --

class PrototypeStore(dict): """ x.prototype.XXXの値を保存するためのクラス """ def setattr(self, name, value): self[name] = value

def __getattr__(self, name):
    return self[name]

class PrototypeMeta(type): """ Prototypeメタクラス(クラス生成時に呼ばれる) """ def new(metacls, cls_name, bases, attrs): cls = type.new(metacls, cls_name, bases, attrs) cls.prototype = PrototypeStore() return cls

class Prototype(object): metaclass = PrototypeMeta

def __getattr__(self, name):
    if name == 'prototype':
        getattr(self.__class__, name)
    else:
        try:
            getattr(object, name)
        except AttributeError:
            return self.__class__.prototype[name]

class TestClass(Prototype): def init(self): pass

first = TestClass() # オブジェクトを作る first.prototype.x = 7 # 'x'をprototypeに割り当てる second = TestClass() # firstと同じTextClassからインスタンスを作る print second.x # first.xと同じオブジェクトを指しているので7になる first.x = 9 # first(インスタンス)の'x'アトリビュートに代入 print first.x # これは7でなく9を返す del first.x # インスタンスアトリビュートを消去 print first.x # prototype.xの返す7になるはず