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
eloah
V2EX  ›  Python

Python 的一个问题

  •  
  •   eloah · 2017-08-04 10:30:58 +08:00 · 2266 次点击
    这是一个创建于 2429 天前的主题,其中的信息可能已经有所发展或是发生改变。

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

    # 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 条回复    2017-08-04 11:26:48 +08:00
    fy
        1
    fy  
       2017-08-04 10:44:28 +08:00   ❤️ 1
    不,__init__是实例化完成后调用的。
    stebest
        2
    stebest  
       2017-08-04 10:47:16 +08:00   ❤️ 1
    只有实例化后才会调用__init__,不实例化是不会执行的。
    yang3yen
        3
    yang3yen  
       2017-08-04 10:48:22 +08:00   ❤️ 1
    class A 的实例 a 是在__new__中创建的,__init__只是用来给新创建的对象 a 赋值
    scriptB0y
        4
    scriptB0y  
       2017-08-04 10:48:31 +08:00   ❤️ 1
    理论上来说,在__init__过程中,对象 A 的实例 a 还没有实例化完成

    第一句就错了
    zhengxiaowai
        5
    zhengxiaowai  
       2017-08-04 10:48:34 +08:00   ❤️ 1
    __new__ 是创建实例
    __init__ 是初始化实例
    eloah
        6
    eloah  
    OP
       2017-08-04 10:49:57 +08:00
    谢谢各位
    看来自己还不够扎实啊,噗
    Kilerd
        7
    Kilerd  
       2017-08-04 11:26:48 +08:00
    python 中的所谓 initialization 包括两个部分 __new__ __init__
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   4300 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 36ms · UTC 10:09 · PVG 18:09 · LAX 03:09 · JFK 06:09
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.