问题描述
为什么构造函数确实被称为构造函数"?它们的目的是什么?它们与类中的方法有何不同?
另外,一个班级中可以有多个 __init__
吗?我尝试了以下方法,有人可以解释一下结果吗?
最后,__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__的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!