栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

小甲鱼零基础python 笔记之 构造和析构(P42)

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

小甲鱼零基础python 笔记之 构造和析构(P42)

 魔法方法: 构造和析构

【Python教程】《零基础入门学习Python》_哔哩哔哩_bilibili

  • __init__(self[,…]) --- 返回值一定是none
  • >>> class A:
    def __init__(self):
    return 2022
     
     
    >>> a2 = A()
    Traceback (most recent call last):
      File "", line 1, in 
        a2 = A()
    TypeError: __init__() should return None, not 'int'

  • __new__(cls[, …]) --- 实例化时真正第一个被调用的方法,它跟其他魔法方法不同,它的第一个参数不是 self 而是这个类(cls),而其他的参数会直接传递给 __init__ 方法的 一般不会去重写,只有在特殊的情况下,eg 继承了一个不可变的类,但是又需要做出修改时. __new__ 方法主要任务时返回一个实例对象.
  • >>> class CapStr(str):
    def __new__(cls, string):
    string = string.upper()                 #将调用字符串的upper()方法并赋给string
    return str.__new__(cls, string)  #将新的string传给老的str的__new__方法,返回的对象给我们新的__new__()方法
     
     
    >>> str1 = CapStr('i am just not capitalized!')
    >>> str1
    'I AM JUST NOT CAPITALIZED!'

  • ''' Celsius to Fahrenheit '''
    class C2F(float):
        def __new__(cls, arg=0.0):
           return float.__new__(cls, arg * 1.8 + 32)
    >>> print(C2F(32))
    89.6

  • 定义一个类继承于 int 类型,并实现一个特殊功能:当传入的参数是字符串的时候,返回该字符串中所有字符的 ASCII 码的和(使用 ord() 获得一个字符的 ASCII 码值)。
    class Nint(int):
            def __new__(cls, arg=0):
                    if isinstance(arg, str):
                            total = 0
                            for each in arg:
                                    total += ord(each)
                            arg = total
                    return int.__new__(cls, arg)

  • __del__(self) --- 垃圾回收机制使用, 当del删除实例对象时,如果这个对象的所有引用都被删除时就会被垃圾回收机制干掉,这个时候才会调用内置的__del__方法。__del__ 方法是当垃圾回收机制回收这个对象的时候调用的
  • >>> class C:
    def __init__(self):
    print('This is init method, I am called')
    def __del__(self):
    print('This is del method, I am called')
     
     
    >>> c1 = C()
    This is init method, I am called
    >>> c2 = c1
    >>> c3 = c2
    >>> del c1
    >>> del c2
    >>> del c3
    This is del method, I am called

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/656578.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号