推荐学习书目
› 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

请问类名()何时会等于类名.__call__() ?

  •  
  •   saximi · Aug 29, 2017 · 2220 views
    This topic created in 3327 days ago, the information mentioned may be changed or developed.
    
    class Foo: 
            def __call__(): 
                    print("call") 
    
    if __name__=='__main__': 
            Foo() 
            print("--------") 
            Foo.__call__() 
    
    
    上面代码输出如下:
    --------
    call
    
    

    请问为何这里 Foo()不等于 Foo.call(),什么情况下才会相等呢? 谢谢

    4 replies  •  2017-08-30 21:11:20 +08:00
    CodeDrift
        1
    CodeDrift  
       Aug 29, 2017
    Foo() 执行的是__init__方法 可以试试这样 f = Foo() f()
    janxin
        3
    janxin  
       Aug 29, 2017 via iPad
    class Foo:
    def __call__(self):
    print("call")

    if __name__=='__main__':
    f = Foo()
    print("--------")
    f()
    saximi
        4
    saximi  
    OP
       Aug 30, 2017
    @janxin 谢谢,我还是有疑问,为何__call__加入 self 参数后就使得 Foo()会调用 Foo.__call__() ,否则这不会调用呢?
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1012 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 18:43 · PVG 02:43 · LAX 11:43 · JFK 14:43
    ♥ Do have faith in what you're doing.