本文相关描述主要是个人的认知和见解,如有不当之处,还望各位大佬指正。
个人其他博客地址:
简书:https://www.jianshu.com/u/d6960089b087
掘金:https://juejin.cn/user/2963939079225608
小钟同学 | 文 【原创】| QQ:308711822
在python 其实我也有所谓的构造函数,类似和java一样的构造函数。对于构造函数是对象一建立就运行,给对象初始化,就包括属性。
但是在python中类有两个类似的功能的魔法函数:
但是在python里面其实真正构造函数是__ new__ ,这两个方法的主要区别在于:
示例代码:
class Aote():
def __new__(cls):
print('我才是构造函数')
return super(Aote, cls).__new__(cls)
def __init__(self):
print("我是奥特之父")
a = Aote()
输出的结果为:
我才是构造函数
我是奥特之父
从顺序上,我们再实例化的时候,类调用的函数的顺序是:先调用了__ new__ ,再调用了__init__,
分析:
@staticmethod # known case of __new__
def __new__(cls, *more): # known special case of object.__new__
""" Create and return a new object. See help(type) for accurate signature. """
pass
类是再调用了类方法__ new__之后,才去创建一个实例并返回:加入我们的不调用return super(Aote, cls).new(cls),会怎么样:
class Aote():
def __new__(cls):
print('我才是构造函数')
def __init__(self):
print("我是奥特之父")
a = Aote()
输出的结果:
我才是构造函数
它没有去调用__ init__
class Aote():
def __new__(cls):
print('我才是构造函数')
# return super(Aote, cls).__new__(cls)
return "什么是"
def __init__(self):
print("我是奥特之父")
def ass(self):
print("来吧!")
a = Aote()
a.ass()
输出结果为:
Traceback (most recent call last):
File "D:/code/python/local_python/AntFlask/ceshi2.py", line 20, in <module>
我才是构造函数
a.ass()
AttributeError: 'str' object has no attribute 'ass'
原文作者:程序员小钟同学;如有侵权,请联系管理员删除。