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

dict.__init__(self)是什么意思

  •  
  •   cc7756789 · May 12, 2015 · 4580 views
    This topic created in 4043 days ago, the information mentioned may be changed or developed.
    好像哪里见到过 dict.__init__(self)之类的用法,在学校threading的时候见到 threading.Thread.__init__(self); 这是什么意思呢?最后的分号有什么作用?网上也查不到相关的东西,另外这个MyThread为什么self.name 自动输出Thread-(1-5),self.name是哪里来的?
    另外程序里面没有join()方法就一直不退出,查过很多资料但是还是理解不了join(),说是阻塞主进程,如果run()是线程,但是主进程又在哪里?

    class MyThread(threading.Thread):
    def __init__(self):
    threading.Thread.__init__(self);
    def run(self):
    print "I am %s" % self.name

    for thread in range(5):
    t = MyThread()
    t.start()
    9 replies    2015-05-20 16:37:43 +08:00
    cc7756789
        1
    cc7756789  
    OP
       May 12, 2015
    在学习threading。。。。。。
    staticor
        2
    staticor  
       May 12, 2015
    self.name 是线程的名 每次 MyThread() 时就会调用 .__init__ 并且对self.name 起名为 Thread- ?

    ?为线程中的排序号

    http://pymotw.com/2/threading/index.html#module-threading 推荐这个 虽然我也不求甚解
    clino
        3
    clino  
       May 12, 2015   ❤️ 1
    先拿父类的__init__先做初始化,如果有自己的初始化要做可以再接着做
    awanabe
        4
    awanabe  
       May 12, 2015
    转自微博: 每日鸡汤:80%的问题都可以通过仔细阅读文档后解决。——莎士比亚

    学会阅读源码...

    Thread init 中 self.__name = str(name or _newname())

    _newname方法如下

    # Helper to generate new thread names
    _counter = 0
    def _newname(template="Thread-%d"):
    global _counter
    _counter = _counter + 1
    return template % _counter
    cc7756789
        5
    cc7756789  
    OP
       May 12, 2015
    @clino 懂了,但是后面的分号有作用吗?我去掉分号也没有出现任何错误。
    clino
        6
    clino  
       May 12, 2015
    @cc7756789 python除了同一行放多个语句的情况,分号是可要可不要的,我一般都不加
    billgreen1
        7
    billgreen1  
       May 12, 2015
    ~~~
    class MyThread(threading.Thread):
    def __init__(self):
    threading.Thread.__init__(self);
    def run(self):
    print "I am %s" % self.name

    if __name__ == "__main__":
    for thread in range(5):
    t = MyThread()
    t.start()
    ~~~

    我实在忍不住了,别拉我~~~
    billgreen1
        8
    billgreen1  
       May 12, 2015
    评论里面不能 markdown ?
    slideclick
        9
    slideclick  
       May 20, 2015
    t.start()是主线程,这个函数运行时,操作系统会创一个新线程去跑run.run怎么可能是主线程。主线程就是if __name__ == '__main__'那个家伙
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   1233 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 41ms · UTC 17:47 · PVG 01:47 · LAX 10:47 · JFK 13:47
    ♥ Do have faith in what you're doing.