from types import FunctionType
def tracer(func):
calls = 0
def onCall(*args, **kwargs):
nonlocal calls
calls += 1
print('call %s to %s' % (calls, func.__name__)) #语句 1
return func(*args, **kwargs) #语句 2
return onCall
class MetaTrace(type):
def __new__(meta, classname, supers, classdict):
for attr, attrval in classdict.items():
print('attr=%s ,attrval=%s'%(attr,attrval))
if type(attrval) is FunctionType:
classdict[attr] = tracer(attrval) #语句 3
return type.__new__(meta, classname, supers, classdict)
class Person(metaclass=MetaTrace):
def __init__(self, name, pay):
print("Person init,name=",name)
self.name = name
self.pay = pay
def giveRaise(self, percent):
print("Person giveRaise,percent=",percent)
self.pay *= (1.0 + percent)
def lastName(self):
print("Person lastName,self=",self)
return self.name.split()[-1]
print('-----------------')
bob = Person('Bob Smith', 50000)
上面代码输出如下:
attr=__module__ ,attrval=__main__
attr=__qualname__ ,attrval=Person
attr=__init__ ,attrval=<function Person.__init__ at 0x01C2BBB8>
attr=giveRaise ,attrval=<function Person.giveRaise at 0x01C2BB70>
attr=lastName ,attrval=<function Person.lastName at 0x01C2BB28>
-----------------
call 1 to __init__
Person init,name= Bob Smith
我的问题是:
执行语句 3 时,当执行到 classdict[__init__] = tracer(<function Person.__init__ at 0x01C2BBB8>) 时,为何不会立即去执行 tracer 定义中的语句 1 和语句 2,使得__init__方法的结果赋值给 classdict[__init__] ?
1
guyskk 2017-08-27 21:34:21 +08:00 via Android
语句 1,2 是 oncall 函数的语句,oncall 执行时才会执行
|