为什么 __init__() 总是先于 __new__() 在 Python 中被调用?
Python 拥有特殊类型的方法,称为魔术方法,名称带下划线且下划线连在一起。
如果我们想讨论魔术方法 __new__,那么显然需要也讨论 __init__ 方法。当实例被创建时,将调用魔术方法 __new__,而当创建实例时,将调用 __init__ 方法来初始化实例。
示例
class X():
_dict = dict()
def __new__(self):
if 'data' in X._dict:
print ("new instance Exists")
return X._dict['data']
else:
print ("magic method New")
return super(X, self).__new__(self)
def __init__(self):
print ("instantiation")
X._dict['data'] = self
print ("")
a1 = X()
a2 = X()
a3 = X()输出
magic method New instantiation new instance Exists instantiation new instance Exists instantiation
要记住的重要事项:__init__ 函数称为构造函数或初始化器,并且在创建类的实例时自动调用它。
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP