先选取了 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,代表对象本身,