请教代码执行顺序的问题

2017-08-27 17:57:33 +08:00
 saximi
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__] ?  

1952 次点击
所在节点    Python
1 条回复
guyskk
2017-08-27 21:34:21 +08:00
语句 1,2 是 oncall 函数的语句,oncall 执行时才会执行

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/386152

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX