推荐学习书目
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 · 3188 views
    This topic created in 3231 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
        1
    fy  
       Aug 4, 2017   ❤️ 1
    不,__init__是实例化完成后调用的。
    stebest
        2
    stebest  
       Aug 4, 2017   ❤️ 1
    只有实例化后才会调用__init__,不实例化是不会执行的。
    yang3yen
        3
    yang3yen  
       Aug 4, 2017   ❤️ 1
    class A 的实例 a 是在__new__中创建的,__init__只是用来给新创建的对象 a 赋值
    scriptB0y
        4
    scriptB0y  
       Aug 4, 2017   ❤️ 1
    理论上来说,在__init__过程中,对象 A 的实例 a 还没有实例化完成

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