Doge log

Abby CTO 雑賀 力王のオフィシャルサイトです

Intercept

Intercept系の実装がわからん・・・。
荒業1

class Super(object):
    def __getattribute__(self,attr):
        method = object.__getattribute__(self,'delegate')
        method(attr)
        return object.__getattribute__(self,attr)
    
    def delegate(self,attr):
        assert 0
        
class Sub(Super):
    def sampleMethod(self):
        return 'sample'
    
    def delegate(self,attr):
        print 'attribute : '+attr+' is hooked'
        
a = Sub()
a.name = 'abc'
print a.name
print a.sampleMethod()

荒業2

# -*- coding: Shift_JIS -*-

#Factory
class Factory:
    def getClass(self,className ,*args):
        c = eval(className)(args)
        #メソッド自身を上書き
        c.getName = self.getMethod(c, 'getName')
        return c
    
    def getMethod(self, c, methodName):
        m = eval('c.'+methodName)
        def method (m=m):
            #メソッドを呼ぶ前に出力
            print 'intercept method begin',
            result = apply(m)
            return result
        return method
    
class Employee:
    def __init__(self,name):
        self.name = name
    
    def getName(self):
        return self.name
    
f = Factory()
e1 = f.getClass('Employee','hoge1')
print e1.name
print e1.getName()
e2 = f.getClass('Employee','hoge2')
print e2.name
print e2.getName()

うくく。