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

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

  •  
  •   saximi · 2017-08-29 21:24:20 +08:00 · 1528 次点击
    这是一个创建于 2424 天前的主题,其中的信息可能已经有所发展或是发生改变。
    
    class Foo: 
            def __call__(): 
                    print("call") 
    
    if __name__=='__main__': 
            Foo() 
            print("--------") 
            Foo.__call__() 
    
    
    上面代码输出如下:
    --------
    call
    
    

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

    4 条回复    2017-08-30 21:11:20 +08:00
    Anybfans
        1
    Anybfans  
       2017-08-29 21:33:11 +08:00
    Foo() 执行的是__init__方法 可以试试这样 f = Foo() f()
    janxin
        3
    janxin  
       2017-08-29 21:43:14 +08:00 via iPad
    class Foo:
    def __call__(self):
    print("call")

    if __name__=='__main__':
    f = Foo()
    print("--------")
    f()
    saximi
        4
    saximi  
    OP
       2017-08-30 21:11:20 +08:00
    @janxin 谢谢,我还是有疑问,为何__call__加入 self 参数后就使得 Foo()会调用 Foo.__call__() ,否则这不会调用呢?
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   1179 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 18:16 · PVG 02:16 · LAX 11:16 · JFK 14:16
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.