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

Python 的一个问题

  •  
  •   eloah · Aug 4, 2017 · 3540 views
    This topic created in 3390 days ago, the information mentioned may be changed or developed.

    今天突然开始纠结起了一个奇怪的问题了

    # Python code
    class A():
        def __init__(self, args):
            self.args = self._init_args(args)
        
        def _init_args(self, args):
            # do something
            return args
            
    a = A(["test", "question"])
    

    这样的逻辑在 Python 中是可以正确的运行的,但是却很奇怪

    理论上来说,在__init__过程中,对象 A 的实例 a 还没有实例化完成.但是上边的代码在 a 的实例化尚未完成时就已经调用了实例 a 的方法_init_args 了,这样做是否有一些隐患?是什么机制使 Python 可以这样处理的?

    7 replies  •  2017-08-04 11:26:48 +08:00
    fy
    fy
    Aug 4, 2017❤️1
    1
    不,__init__是实例化完成后调用的。
    stebest
    stebest
    Aug 4, 2017❤️1
    2
    只有实例化后才会调用__init__,不实例化是不会执行的。
    yang3yen
    yang3yen
    Aug 4, 2017❤️1
    3
    class A 的实例 a 是在__new__中创建的,__init__只是用来给新创建的对象 a 赋值
    scriptB0y
    scriptB0y
    Aug 4, 2017❤️1
    4
    理论上来说,在__init__过程中,对象 A 的实例 a 还没有实例化完成

    第一句就错了
    zhengxiaowai
    zhengxiaowai
    Aug 4, 2017❤️1
    5
    __new__ 是创建实例
    __init__ 是初始化实例
    eloah
    eloah
    OP
    Aug 4, 2017
    6
    谢谢各位
    看来自己还不够扎实啊,噗
    Kilerd
    Kilerd
    Aug 4, 2017
    7
    python 中的所谓 initialization 包括两个部分 __new__ __init__
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1374 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 35ms · UTC 16:46 · PVG 00:46 · LAX 08:46 · JFK 11:46
    ♥ Do have faith in what you're doing.