先选取了 6 个自己认为值得玩味的 python 代码,希望对正在学习 python 的你有所帮助。
1、类有两个方法,一个是 __new__,一个是 __init__,有什么区别,哪个会先执行呢?
class test(object):
def __init__(self):
print("test -> __init__")
def __new__(cls):
print("test ->__new__")
return super().__new__(cls)
a = test()
运行结果如下:
test ->__new__
test -> __init__
再来看另一个例子
class test2(object):
def __init__(self):
print("test2 -> __init__")
def __new__(cls):
print("test2 ->__new__")
return object()
b = test2()
运行结果如下:
test2 ->__new__
这里给出官方的解释:__init__ 作用是类实例进行初始化,第一个参数为 self,代表对象本身,可以没有返回值。__new__ 则是返回一个新的类的实例,第一个参数是 cls 代表该类本身,必须有返回值。很明显,类先实例化才能产能对象,显然是 __new__ 先执行,然后再 __