__init__作为构造函数? [英] __init__ as a constructor?

查看:200
本文介绍了__init__作为构造函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

深入Python -


这将是诱人,但不正确的
调用这个
类的构造函数。它是诱人的,因为它看起来
像一个构造函数(按照惯例,
__ init __ 是为类定义的第一个方法),行为像一个

新创建的类的实例中执行的第一段代码),
甚至听起来像一个(init
当然建议一个构造函数ish
自然)。不正确,因为对象
已经由
构造时间 __ init __ 被调用,并且您
已经有一个对
类的新实例。

It would be tempting but incorrect to call this the constructor of the class. It's tempting, because it looks like a constructor (by convention, __init__ is the first method defined for the class), acts like one (it's the first piece of code executed in a newly created instance of the class), and even sounds like one ("init" certainly suggests a constructor-ish nature). Incorrect, because the object has already been constructed by the time __init__ is called, and you already have a valid reference to the new instance of the class.

引用建议调用 __ init __ 作为构造函数,因为对象已经被调用 __ init __ 的时间构造。但!我一直受到的印象是,构造函数只有在对象被构造之后才被调用,因为它实质上用于初始化实例的数据成员,如果对象没有存在于构造函数被调用时? (来自C ++ / Java背景)

Quote suggests it is incorrect to call __init__ as a constructor because the object is already constructed by the time __init__ is called. But! I have always been under the impression that the constructor is called only after the object is constructed because it is essentially used to initialized the data members of the instance which wouldn't make sense if the object didn't exist by the time constructor was called? (coming from C++/Java background)

推荐答案

如果你有一个类 Foo 然后:

  • Foo() is the constructor
  • Foo.__init__() is the initializer
  • Foo.__new__() is the allocator

Python对象的构造只是一个新实例的分配,

Construction of a Python object is simply allocation of a new instance followed by initialization of said instance.

这篇关于__init__作为构造函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆