V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
saximi
V2EX  ›  Python

请教代码执行顺序的问题

  •  
  •   saximi · 2017-08-27 17:57:33 +08:00 · 1924 次点击
    这是一个创建于 2405 天前的主题,其中的信息可能已经有所发展或是发生改变。
    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 条回复    2017-08-27 21:34:21 +08:00
    guyskk
        1
    guyskk  
       2017-08-27 21:34:21 +08:00 via Android
    语句 1,2 是 oncall 函数的语句,oncall 执行时才会执行
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1054 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 22:39 · PVG 06:39 · LAX 15:39 · JFK 18:39
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.