Python 构造函数和 __init__ [英] Python constructors and __init__

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

问题描述

为什么构造函数确实被称为构造函数"?它们的目的是什么?它们与类中的方法有何不同?

另外,一个班级中可以有多个 __init__ 吗?我尝试了以下方法,有人可以解释一下结果吗?

<预><代码>>>>课堂测试:def __init__(self):打印init 1"def __init__(self):打印init 2">>>s=测试()初始化 2

最后,__init__ 是运算符重载吗?

解决方案

Python 中没有函数重载,这意味着不能有多个同名但参数不同的函数.

在您的代码示例中,您没有重载 __init__().发生的情况是第二个定义重新绑定名称__init__到新方法,使第一个方法无法访问.

至于您关于构造函数的一般问题,维基百科是一个很好的初始点.对于特定于 Python 的内容,我强烈推荐 Python 文档.

Why are constructors indeed called "Constructors"? What is their purpose and how are they different from methods in a class?

Also, can there be more that one __init__ in a class? I tried the following, can someone please explain the result?

>>> class test:
    def __init__(self):
        print "init 1"
    def __init__(self):
        print "init 2"

>>> s=test()
init 2

Finally, is __init__ an operator overloader?

解决方案

There is no function overloading in Python, meaning that you can't have multiple functions with the same name but different arguments.

In your code example, you're not overloading __init__(). What happens is that the second definition rebinds the name __init__ to the new method, rendering the first method inaccessible.

As to your general question about constructors, Wikipedia is a good starting point. For Python-specific stuff, I highly recommend the Python docs.

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

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