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

请教一个(*args, **kwargs)参数传递的问题

  •  
  •   saximi · 2017-08-21 21:49:18 +08:00 · 1619 次点击
    这是一个创建于 2457 天前的主题,其中的信息可能已经有所发展或是发生改变。

    class tracer(object):

        def __init__(self, func):   
    
                self.calls = 0   
    
                self.func = func 
    
        def __call__(self, *args, **kwargs):  
    
                self.calls += 1 
    
                print('call %s to %s' % (self.calls, self.func.__name__)) 
    
                return self.func(*args, **kwargs) 
    
        def __get__(self, instance, owner):   
    
                def wrapper(*args, **kwargs):  
    
                        print('wrapper:args=%s ,kwargs=%s'% (args,kwargs)) 
    
                        return self(instance, *args, **kwargs)   
    
                return wrapper 
    

    class Person:

        def __init__(self, name, pay): 
    
                self.name = name 
    
                self.pay = pay 
    
        @tracer 
    
        def giveRaise(self, percent):  
    
                self.pay *= (1.0+percent) 
    
                print("pay=",self.pay) 
    

    bob = Person('Bob Smith', 50000)

    bob.giveRaise(.10)

    上面代码的输出如下:

    wrapper:args=(0.1,) ,kwargs={}

    call 1 to giveRaise

    pay= 55000.00000000001

    我的问题是:wrapper 方法是在__get__方法内定义的,但是__get__方法并没有接收参数(*args, **kwargs),为何 wrapper 方法的(*args, **kwargs)参数会有值呢?

    1 条回复    2017-08-21 22:11:54 +08:00
    Trim21
        1
    Trim21  
       2017-08-21 22:11:54 +08:00
    @tracer 相当于后面函数的装饰器了,你的 giveRaise 函数已经被 wrapper 替代了
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1162 人在线   最高记录 6547   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 18:36 · PVG 02:36 · LAX 11:36 · JFK 14:36
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.