ITPub博客

首页 > 数据库 > 数据库开发技术 > python面向对象编程篇(7):类魔法函数之__init__,__new__方法分析

python面向对象编程篇(7):类魔法函数之__init__,__new__方法分析

原创 数据库开发技术 作者:程序员小钟同学 时间:2021-03-15 18:02:50 0 删除 编辑

本文相关描述主要是个人的认知和见解,如有不当之处,还望各位大佬指正。

个人其他博客地址:

简书:https://www.jianshu.com/u/d6960089b087

掘金:https://juejin.cn/user/2963939079225608

小钟同学 | 文 【原创】| QQ:308711822

1、前言

在python 其实我也有所谓的构造函数,类似和java一样的构造函数。对于构造函数是对象一建立就运行,给对象初始化,就包括属性。

2、python中的构造函数分析和总结

但是在python中类有两个类似的功能的魔法函数:

  • 一个是, __ new__
  • 另一个是 __ init__

但是在python里面其实真正构造函数是__ new__ ,这两个方法的主要区别在于:

  • __ new__ 负责对象的创建
  • __ init__ 负责对象的初始化

示例代码:

class Aote():

    def __new__(cls):
        print('我才是构造函数')
        return super(Aote, cls).__new__(cls)

    def __init__(self):
        print("我是奥特之父")

a =  Aote()

输出的结果为:

我才是构造函数
我是奥特之父

从顺序上,我们再实例化的时候,类调用的函数的顺序是:先调用了__ new__ ,再调用了__init__,

分析:

  • __ new__ 它传入的参数是 cls,所以它是一个类方法
    @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

  • __ init__ 它传入的是self(传入self说明是已经创建好对象了),所以它是一个实例的方法。

3. 不调用return super(Aote, cls).new(cls)的情况

类是再调用了类方法__ new__之后,才去创建一个实例并返回:加入我们的不调用return super(Aote, cls).new(cls),会怎么样:

class Aote():

    def __new__(cls):
        print('我才是构造函数')


    def __init__(self):
        print("我是奥特之父")

a =  Aote()

输出的结果:

我才是构造函数

它没有去调用__ init__

3. __ new__(cls)返回不是对象的示例的情况


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'


原文作者:程序员小钟同学;如有侵权,请联系管理员删除。

请登录后发表评论 登录
全部评论

注册时间:2021-02-20

  • 博文量
    224
  • 访问量
    111698